Maven搭建Struts2 Spring Hibernate4框架
Struts2版本 2.3.24,Spring版本4.0.4.RELEASE,Hibernate版本4..2.3.Final。搭建之前刻意查看了下自己电脑下载好的jar包,不用maven的时候就是用这些版本,估计用maven也不会出错,就用这个了。
1:pom.xml:
1)Struts2:
struts2-core:Struts2的核心jar包;
struts2-convention-plugin:convention-plugin插件,使用了这个插件之后,就可以采用注解的方式配置Action,虽然我不大爱用注解吧。
struts2-config-browser-plugin:config-browser-plugin插件,使用了这个插件之后,就可以很方便的浏览项目中的所有action及其与 jsp view的映射。http://localhost:8080/SSH/config-browser/actionNames.action,SSH为项目名。
struts2-spring-plugin:Struts2和Spring整合插件 ,这个一定要有。
2)Spring:
spring-core:Spring的核心jar包
spring-context:上下文jar包
spring-jdbc:连接jdbc的jar包,一般在获取dataSource时使用。
spring-beans:很明显,beans的jar包,必须有
spring-web:web的jar包,没想到在哪用了,我又没用spring mvc。
spring-expression:这个是表达式的。
spring-orm:orm对象关系映射,和hibernate有关,这个很重要。不同于struts2与spring整合需要struts2-spring-plugin,spring-orm就是spring和hibernate的整合。
3)Hibernate:
hibernate-core:hibernate和核心jar包
4)MySQL:
mysql-connector-java:我连接的是mysql数据库,网上说要是连接oracle,需要把jar包下载到本地仓库,用maven不会下载oracle的jar包,具体怎么配置maven的本地仓库我是忘记了,不过我记得我的本地仓库在哪。
5)C3P0数据库连接池
c3p0:hibernate就是用的这个数据库连接池,所以我显式的用c3p0来配置dataSource
6)Aspectj
aspectjweaver:跟事务那里有关,有个织入的过程,这个可以看spring的事务管理
7)javax.servlet
javax.servlet-api:没它项目必然报错
8)junit
junit:单元测试
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Maven</groupId> <artifactId>SSH</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SSH Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <!-- 只在编译时和测试时运行 --> <scope>provided</scope> </dependency> <!-- Struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.24</version> <!-- 这里的 exclusions 是排除包,因为 Struts2中有javassist,Hibernate中也有javassist, 所以如果要整合Hibernate,一定要排除掉Struts2中的javassist,否则就冲突了。 <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> --> <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <!-- convention-plugin插件,使用了这个插件之后,就可以采用注解的方式配置Action --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.24</version> </dependency> <!--config-browser-plugin插件,使用了这个插件之后,就可以很方便的浏览项目中的所有action及其与 jsp view的映射 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-config-browser-plugin</artifactId> <version>2.3.24</version> </dependency> <!-- Struts2和Spring整合插件 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.24</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.0.4.RELEASE</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.3.Final</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- Aspectj --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> </dependencies> <build> <finalName>SSH</finalName> </build> </project>
2:web.xml
1)Spring:
在这里配置spring的监听器,配置文件的位置,不需要配置spring的servlet,页面流用struts2
2)openSessionInViewFilter
还不大懂,后续再补充
3)Struts2:
配置Struts2的核心过滤器
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Spring --> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring_beans.xml,classpath:spring_hibernate.xml</param-value> </context-param> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 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> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- Struts2 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
3:struts.xml
Sturts2的配置文件,初步一看内容挺多,必须有的是package,没有包可不行。
DynamicMethodInvocation也得有,后面用到时会说这个。
<?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> <!-- 所有匹配*.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="default" extends="struts-default"> </package> </struts>
4:jdbc.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=gacl #jdbc_password=xdp hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/zhao?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc_username=root jdbc_password=数据库密码 #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/sshe #jdbc_username=sa #jdbc_password=123456 #jndiName=java:comp/env/dataSourceName hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true
5:spring
spring-beans.xml是用来配置spring用到的bean的,spring-hibernate是spring和hibernate的整合。
spring-beans.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- 引入属性文件,config.properties位于src/main/resources目录下 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="com.zhao.DAO.impl,com.zhao.Biz.impl" /> </beans>
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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource"> <property name="driverClass" value="${driverClassName}" /> <property name="jdbcUrl" value="${jdbc_url}" /> <property name="user" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <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> <property name="mappingLocations" value="classpath:com/zhao/entity/*.hbm.xml"></property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 拦截器方式配置事物 --> <tx:advice id="txAdvice" 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="pointCut" expression="execution(* com.zhao.Biz.impl.*Impl.*(..))" /> <aop:advisor pointcut-ref="pointCut" advice-ref="txAdvice" /> </aop:config> </beans>
至此,配置文件什么的,差不多是完成了,现在看下目录结构
6:代码
1)com.zhao.entity是实体类,里面有Student类和其对应的对象关系映射文件,Student类里写了好几个构造方法,是为了测试方便,其实没必要写这么多。
package com.zhao.entity; import java.io.Serializable; public class Student implements Serializable { private Integer stu_id; private String stu_name; private String stu_gender; public Student() { } public Student(Integer stu_id, String stu_name, String stu_gender) { this.stu_id = stu_id; this.stu_name = stu_name; this.stu_gender = stu_gender; } public Student(String stu_name, String stu_gender) { this.stu_name = stu_name; this.stu_gender = stu_gender; } public Integer getStu_id() { return stu_id; } public void setStu_id(Integer stu_id) { this.stu_id = stu_id; } public String getStu_name() { return stu_name; } public void setStu_name(String stu_name) { this.stu_name = stu_name; } public String getStu_gender() { return stu_gender; } public void setStu_gender(String stu_gender) { this.stu_gender = stu_gender; } @Override public String toString() { return "Student [stu_id=" + stu_id + ", stu_name=" + stu_name + ", stu_gender=" + stu_gender + "]"; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2016-4-12 20:59:43 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.zhao.entity.Student" table="STUDENT"> <id name="stu_id" type="java.lang.Integer"> <column name="STU_ID" /> <generator class="native" /> </id> <property name="stu_name" type="java.lang.String"> <column name="STU_NAME" /> </property> <property name="stu_gender" type="java.lang.String"> <column name="STU_GENDER" /> </property> </class> </hibernate-mapping>
2)com.zhao.DAO和com.zhao.DAO.impl是数据库操作的接口包和实现类包,在具体的实现类中,要有对数据库的操作,所以自动装配sessionFactory。@Repository用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean,但是需要在 XML 配置文件中启用Bean 的自动扫描功能,这可以通过<context:component-scan/>实现,现在再看看spring-beans.xml,肯定能找到这句代码。
package com.zhao.DAO; import java.io.Serializable; import com.zhao.entity.Student; public interface StudentDAO { public Serializable save(Student student); }
package com.zhao.DAO.impl; import java.io.Serializable; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.zhao.DAO.StudentDAO; import com.zhao.entity.Student; @Repository("studentDAO") public class StudentDAOImpl implements StudentDAO{ @Autowired private SessionFactory sessionFactory; @Override public Serializable save(Student student) { return sessionFactory.getCurrentSession().save(student); } }
3)com.zhao.Biz和com.zhao.Biz.impl是业务逻辑接口和其具体的实现类,@Service 通常作用在业务层,这里的注解和刚才数据库层的就不一样了。当然自动装配是肯定的。
package com.zhao.Biz; import java.io.Serializable; import com.zhao.entity.Student; public interface StudentBiz { public Serializable save(Student student); }
package com.zhao.Biz.impl; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zhao.Biz.StudentBiz; import com.zhao.DAO.StudentDAO; import com.zhao.entity.Student; @Service("studentBiz") public class StudentBizImpl implements StudentBiz { @Autowired private StudentDAO studentDAO; @Override public Serializable save(Student student) { return studentDAO.save(student); } }
4)com.zhao.action里面是struts2的action,这里用的是注解,倒没觉得有什么好,没有struts.xml看的清楚。action肯定要有package,还要有命名空间namespace。具体页面跳转,逻辑视图怎么找到物理视图资源,过几天再整理。ModelDriver<Student>模型驱动的形式获取了页面提交的数据,看来近期有必要整理下struts2获取数据的几种方式了。
package com.zhao.action; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.zhao.Biz.StudentBiz; import com.zhao.DAO.StudentDAO; import com.zhao.entity.Student; @ParentPackage("default") @Action(value="login") @Namespace("/") public class LoginAction extends ActionSupport implements ModelDriven<Student> { @Autowired private StudentBiz biz; private Student student = new Student(); public String login() throws Exception { System.out.println(biz.save(student)); System.out.println(student); return "login"; } @Override public Student getModel() { if (student == null) { student = new Student(); } return student; } }
5)前端页面,index.jsp中input的name和Student实体类中的属性名是一样的,注意看我们表单的action:"login!login.action",以.action结尾是因为我们定义的struts2默认拦截.action结尾的请求,无论是在web.xml还是struts.xml我们都是这么配置的,!之前是指向action的,在com.zhao.action.LoginAction中配置了这个名字,看LoginAction,有注解@Action,里面的value就是这个值,如果没配置value,默认就是类名删去Action的那部分,当然 也是login。!之后是我们在这个Action里具体用哪个方法,也就是我们的方法名,如果想用这种方式动态的指定方法,而不是用默认的execute()方法的话,必须在struts.xml中配置动态方法调用,也就是struts.enable.DynamicMethodInvocation为true,这个单词的意思就是动态方法调用。在WEB-INF的content目录下还有login.jsp,这个名字跟上面那个action返回的String是一样的。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title> </head> <body> <form action="login!login.action" method="post"> Name: <input type="text" name="stu_name"/> <br/> Password: <input type="password" name="stu_password"/> <br/> <input type="submit" value="Submit"/> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 搭建成功 </body> </html>
接下来看看效果
7:效果
看来这个动态方法调用没那么好用,上面那个URL太可怕了,近期得把它改改。
数字6是保存到数据库中自动增长的主键值,Serializable。
至于单元测试什么的,写代码的时候写了,这里就不写了。至此,告一段落。