HHS整合(Struts2+Spring+Hibernate)
一、搭建Struts2
具体步骤可以参考Struts2官网 如何创建Struts 2 Web应用程序: https://struts.apache.org/getting-started/how-to-create-a-struts2-web-application.html
1、在maven的pom.xml添加struts2-core的依赖节点
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.20</version> </dependency>
2、添加日志记录
log4j2.xml
在src/main/resources
包含以下内容的文件夹中设置配置
<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </Console> </Appenders> <Loggers> <Logger name="com.opensymphony.xwork2" level="debug"/> <Logger name="org.apache.struts2" level="debug"/> <Root level="warn"> <AppenderRef ref="STDOUT"/> </Root> </Loggers> </Configuration>
3、添加log4j依赖节点
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.9.0</version> </dependency>
4、添加Struts2 servlet过滤器
在web.xml中添加过滤器
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Basic Struts2</display-name> <welcome-file-list> <welcome-file>index</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
5、创建struts.xml核心配置文件,放在src/main/resources
文件夹中
在struts.xml文件中我们开启动态方法调用
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <package name="basicstruts2" extends="struts-default" strict-method-invocation="false"> <action name="index"> <result>/index.jsp</result> </action> </package> </struts>
这样我们的struts2就搭建好了
6、Struts2的hello world 编写测试类
struts.xml中配置action
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <package name="basicstruts2" extends="struts-default" strict-method-invocation="false"> <action name="index"> <result>/index.jsp</result> </action> <action name="test" class="com.blb.action.TestAction"> <result name="success">/index.jsp</result> </action> </package> </struts>
编写测试类继承ActionSupport
package com.blb.action; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport { public String hello(){ return SUCCESS; } }
运行项目,访问地址: localhost:8080/项目名/test!hello
这样Struts2的环境就搭建完成了
二、搭建Spring
1、在项目中添加spring-context依赖节点
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.7.RELEASE</version> </dependency>
因为是web项目,我们还需要导入spring-webmvc依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.7.RELEASE</version> </dependency>
2、创建applicationContext.xml核心配置文件,放在src/main/resources
文件夹中
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
3、在web.xml文件中添加spring监听,使spring在程序运行时启动
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
这样我们的spring就搭建完成了
三、整合Struts2+Spring
1、在项目中添加struts2-spring-plugin依赖节点
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.20</version> </dependency>
由于struts2-spring-plugin依赖包含spring-context,spring-web,struts2-core依赖,所以我们需要把这三个依赖移除
2、在applicationContext.xml文件中注入我们的TestAction类
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="TestAction" class="com.blb.action.TestAction"/> </beans>
3、在struts.xml文件中把action中的class属性值改成bean的id
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <package name="basicstruts2" extends="struts-default" strict-method-invocation="false"> <action name="index"> <result>/index.jsp</result> </action> <action name="test" class="TestAction"> <result name="success">/index.jsp</result> </action> </package> </struts>
重新运行项目,访问地址,成功访问到index.jsp
四、搭建Hibernate
1、在项目中添加 hibernate-cor 依赖
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.3.Final</version> </dependency>
hibernate属于orm框架,所以还需要添加mysql依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
2、创建hibernate.cfg.xml核心配置文件,放在src/main/resources
文件夹中
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 方言 使用哪个数据库 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/autho?useUnicode=true&characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- 显示sql语句 --> <property name="show_sql">true</property> <!-- 实体类 --> <mapping class="com.blb.entity.User"/> </session-factory> </hibernate-configuration>
3、编写一个User实体类
这里就直接使用注解的方式,不采用hibernate映射文件的方式
package com.blb.entity; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="s_user") public class User { @Id private String id; private String username; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "User [id=" + id + ", username=" + username + "]"; } }
hibernate就搭建完成了
五、Spring+Hibernate
1、集成Spring和hibernate,需要在spring的核心配置文件中配置数据源
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"> </property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"> </property> <property name="user" value="root" /> <property name="password" value="root" /> <property name="maxPoolSize" value="20" /> <property name="minPoolSize" value="2" /> <property name="initialPoolSize"> <value>10</value> </property> <property name="maxIdleTime" value="60" /> <property name="idleConnectionTestPeriod" value="60"></property> <property name="acquireIncrement"> <value>5</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocations" value="classpath:hibernate.cfg.xml"/> </bean>
由于使用了 c3p0数据源 和 org.springframework.orm.hibernate5.LocalSessionFactoryBean ,所以我们需要添加c3p0依赖和spring-orm
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.1.7.RELEASE</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
这时我们需要把hibernate核心配置文件中的jdbc配置删除
2、如何使用SessionFactory
在spring核心配置文件中加入包扫描
在类中从ioc容器中获取SessionFactory
@Autowired private SessionFactory sessionFactory;
如此就SSH就搭建完成了
六、使用注解代替struts.xml文件
1、首先将我们的action包中的action类上添加一个@Controller注解和一个@Scope("prototype")注解
2、在类中的方法上面添加@Action(value="add")注解 value的值可以与方法名不一致
3、使用注解返回SUCCESS和ERROR,j将下面代码放在方法上面
@Action(value="select",results={@Result(name="success",location="/index.jsp"),@Result(name="error",location="/500.jsp")})
4、删除struts.xml核心配置文件
七、SSH添加注解式事务
1、在spring的核心配置文件中添加如下代码
<!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 开启注解器事务 --> <tx:annotation-driven transaction-manager="transactionManager" />
之后的spring核心配置文件应该是这个样
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <context:component-scan base-package="com.blb"/> <bean id="AppAction" class="com.blb.action.App"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"> </property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"> </property> <property name="user" value="root" /> <property name="password" value="root" /> <property name="maxPoolSize" value="20" /> <property name="minPoolSize" value="2" /> <property name="initialPoolSize"> <value>10</value> </property> <property name="maxIdleTime" value="60" /> <property name="idleConnectionTestPeriod" value="60"></property> <property name="acquireIncrement"> <value>5</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocations" value="classpath:hibernate.cfg.xml"/> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 开启注解器事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
2、在对数据库进行增删改的方法上面加上
@Transactional(rollbackFor=Exception.class)