SSH项目在Maven下整合

 
引用
一:Maven的安装: POM.xml P:project O:Object M:Model 在pom.xml文件中有modelVersion,maven2和maven3一定是4.0.0版本 groupId,artifactId和version是必须写的 maven约定的源文件的目录为:src/main/java/com.sym.HelloWord.java 资源文件目录为:src/main/resources/spring.xml 测试源文件目录为:src/test/java/com.sym.Test.java 测试资源文件目录为:src/test/resources/spring.xml maven的配置和JDK是完全一样的,也需要配置环境变量 在命令行中输入:mvn -version可以测试maven是否测试成功 在项目的开发的过程中预先设置: 1.对项目右击属性,可以选择为UTF-8 2.右击选择buildpath对JDK进行编辑,选择第三项默认的工作区间JDK版本 3.安装log打印的插件log4e-1.3.3和SVN版本的控制插件site-1.8.7:复制到myeclipse的安装目录下的dropins下,然后重启Myeclipse,右击能够出现share project等选项,表明SVN安装成功。右击出现log4e表明log打印插件安装成功,选择Decare log,引入log4j.properties log4j.rootLogger=INFO,A1,R log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.Target=System.out log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=[%c]%m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=sshe.log log4j.appender.R.MaxFileSize=10MB log4j.appender.R.Threshold=ALL log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n 然后在pom.xml加入: <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> 二.Spring3的配置: 1.引入spring的jar包,通过在pom.xml文件中依赖。另外查找相关的jar包可以在www.search.maven.org仓库里面查找 <!-- spring3 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.1.2.RELEASE</version> </dependency> 2.在src/main/resources里面加入spring.xml,因为采用的是annotation的方式,示例: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="sym.dao,sym.service" /> </beans> serviceImpl中的文件为 @Service("userService") public class UserServiceImpl implements UserServiceI { public void test(){ System.out.println("测试成功"); } } 3,采用Junit测试 需要再pom.xml里面加入junit的jar包 <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11-beta-1</version> <scope>test</scope> </dependency> 测试代码: public class TestSpring { @Test public void test() { ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] { "classpath:spring.xml" }); UserServiceI userService = (UserServiceI) ac.getBean("userService"); userService.test(); } } 三.Struts2和Spring3的整合: 1.在pom.xml中加入struts2的依赖包: <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.4.1</version> //若与hibernate结合需要排除,不结合不需要排除 <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <!--通过spring来控制struts2--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.4.1</version> </dependency> <!--使用annotation--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.4.1</version> </dependency> 2.在resources中加入struts.xml,内容如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 指定由spring负责action对象的创建 --> <constant name="struts.objectFactory" value="spring" /> <!-- 所有匹配*.action的请求都由struts2处理 --> <constant name="struts.action.extension" value="action" /> <!-- 是否启用开发模式 --> <constant name="struts.devMode" value="true" /> <!-- struts配置文件改动后,是否重新加载 --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 设置浏览器是否缓存静态内容 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 请求参数的编码方式 --> <constant name="struts.i18n.encoding" value="utf-8" /> <!-- 每次HTTP请求系统都重新加载资源文件,有助于开发 --> <constant name="struts.i18n.reload" value="true" /> <!-- 文件上传最大值 --> <constant name="struts.multipart.maxSize" value="104857600" /> <!-- 让struts2支持动态方法调用 --> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <!-- Action名称中是否还是用斜线 --> <constant name="struts.enable.SlashesInActionNames" value="false" /> <!-- 允许标签中使用表达式语法 --> <constant name="struts.tag.altSyntax" value="true" /> <!-- 对于WebLogic,Orion,OC4J此属性应该设置成true --> <constant name="struts.dispatcher.parametersWorkaround" value="false" /> <!-- 只有此行是必须 --> <package name="basePackage" extends="struts-default"> </package> </struts> 3.在web.xml中加入过滤器: <!-- Struts2配置 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> 4.代码 @parentPackage("basePackage") //此时访问为XXXproject/userAction!reg.action,若@Namespace("/demo"),则为XXXproject/demo/userAction!reg.action @Namespace("/") @Action(value = "userAction") public class UserAction extends BaseAction implements ModelDriven<User> { private User user = new User(); @Override public User getModel() { return user; } private static final Logger logger = Logger.getLogger(UserAction.class); private UserServiceI userService; public UserServiceI getUserService() { return userService; } //把service注入到action @Autowired public void setUserService(UserServiceI userService) { this.userService = userService; } public void reg() { Json j = new Json(); try { userService.save(user); j.setSuccess(true); j.setMsg("注册成功!"); } catch (Exception e) { j.setMsg(e.getMessage()); } super.writeJson(j); } } 四.Hibernate的整合 1.在pom.xml中导入jar包 <!-- hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.1.7.Final</version> </dependency>
2.在resource中加入文件:spring-hibernate.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- JNDI方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <value>sy.model</value> </list> </property> <!-- 自动扫描hbm方式配置的hibernate文件和.hbm文件 --> <!-- <property name="mappingDirectoryLocations"> <list> <value>classpath:sy/hbm</value> </list> </property> --> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" /> <tx:method name="save*" /> <tx:method name="update*" /> <tx:method name="modify*" /> <tx:method name="edit*" /> <tx:method name="delete*" /> <tx:method name="remove*" /> <tx:method name="repair" /> <tx:method name="deleteAndRepair" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans> 本次的数据源参数设置在resource中的config.properties中: hibernate.dialect=org.hibernate.dialect.OracleDialect driverClassName=oracle.jdbc.driver.OracleDriver validationQuery=SELECT 1 FROM DUAL jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl jdbc_username=sshe jdbc_password=sshe #hibernate.dialect=org.hibernate.dialect.MySQLDialect #driverClassName=com.mysql.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:mysql://localhost:3306/sy?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull #jdbc_username=sypro #jdbc_password=sypro #hibernate.dialect=org.hibernate.dialect.SQLServerDialect #driverClassName=net.sourceforge.jtds.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy #jdbc_username=sa #jdbc_password=123456 #jndiName=java:comp/env/dataSourceName hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false sessionInfoName=sessionInfo uploadFieldName=filedata uploadFileMaxSize=20971520 uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid uploadDirectory=attached 3,写入代码 @Repository("baseDao") public class BaseDaoImpl<T> implements BaseDaoI<T> { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private Session getCurrentSession() { return this.sessionFactory.getCurrentSession(); } @Override public Serializable save(T o) { return this.getCurrentSession().save(o); } } Action中的代码: @Service("userService") public class UserServiceImpl implements UserServiceI { private static final Logger logger = Logger.getLogger(UserServiceImpl.class); private BaseDaoI<Tuser> userDao; public BaseDaoI<Tuser> getUserDao() { return userDao; } @Autowired public void setUserDao(BaseDaoI<Tuser> userDao) { this.userDao = userDao; } @Override public User save(User user) { Tuser t = new Tuser(); BeanUtils.copyProperties(user, t, new String[] { "pwd" }); t.setId(UUID.randomUUID().toString()); t.setCreatedatetime(new Date()); t.setPwd(Encrypt.e(user.getPwd())); userDao.save(t); BeanUtils.copyProperties(t, user); return user; } 4.在web.xml中的配置: <!-- spring配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value> </context-param> <!-- openSessionInView配置 --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 修复数据库监听器 --> <listener> <listener-class>sy.listener.RepairListener</listener-class> </listener>

你可能感兴趣的:(maven)