首先来看需要的jar包:
在web.xml中的配置:
<?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"> <!-- 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>/*</url-pattern> </filter-mapping> <!-- OpenSession In View --> <filter> <filter-name>openSessionInView</filter-name> <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring配置 指定spring配置文件位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:ApplicationContext.xml</param-value> </context-param> <!-- 实例化Spring容器 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
在Struts2的配置文件struts.xml中的配置:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="myStruts" extends="struts-default" namespace="/"> <!-- 使用通配符 --> <action name="*_*" class="{1}" method="{2}"> <result name="list">/{1}/list.jsp</result> <result name="input">/{1}/update.jsp</result> <result name="reload" type="chain">{1}_list</result> </action> </package> </struts>
需要注意的是class的名字要和Spring中管理Action的Bean的名字相同。
由于需要将Struts2的Action交给Spring去管理,我们在struts.properties配置文件中加入:
struts.objectFactory=spring
再来看看Spring的配置文件ApplicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- 启用自动扫描 --> <context:component-scan base-package="com.javaonroad"></context:component-scan> <!-- 事务管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql:///struts2" /> <property name="maxIdleTime" value="25000" /> <property name="properties"> <props> <prop key="user">root</prop> <prop key="password">root</prop> <prop key="c3p0.acquire_increment">2</prop> <prop key="c3p0.max_size">20</prop> <prop key="c3p0.min_size">1</prop> </props> </property> </bean> <!-- 定义Hibernate SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- dataSource可以为任意的数据源 例如DBCP、C3P0 --> <property name="dataSource" ref="dataSource"></property> <!-- 映射文件路径 --> <property name="mappingResources"> <value>com/javaonroad/pojo/User.hbm.xml</value> </property> <!-- 其他的Hibernate常用配置 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> </beans>
由于启用了自动扫描,所以在dao、service以及action中都要使用注解进行标记:
DAO类:
package com.javaonroad.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.javaonroad.pojo.User; @Repository public class UserDAO { @Resource private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } public void save(User user) { getSession().save(user); } public void update(User user) { getSession().update(user); } public User get(int id) { return (User) getSession().get(User.class, id); } public User findUserByNameAndPwd(User user) { String hql = "from User where name = :name and pwd = :pwd"; Query query = getSession().createQuery(hql); query.setString("name", user.getName()); query.setString("pwd", user.getPwd()); return (User) query.uniqueResult(); } public void delete(int id) { getSession().delete(get(id)); } @SuppressWarnings("unchecked") public List<User> findAll() { Criteria cri = getSession().createCriteria(User.class); List<User> list = cri.list(); return list; } }
Service类:
其中事务同样采用注解:
package com.javaonroad.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.javaonroad.dao.UserDAO; import com.javaonroad.pojo.User; @Transactional @Service public class UserService { @Resource private UserDAO userDAO; public User login(User user) { return userDAO.findUserByNameAndPwd(user); } public void save(User user) { userDAO.save(user); } public void update(User user) { userDAO.update(user); } public User get(String id) { return userDAO.get(Integer.valueOf(id)); } public void delete(String id) { userDAO.delete(Integer.valueOf(id)); } public List<User> findAll() { return userDAO.findAll(); } }
最后是我们的Action类,由于Struts2的Action的线程安全的所以在注解的时候需要改变Spring默认的Scope属性:
package com.javaonroad.web; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.javaonroad.pojo.User; import com.javaonroad.service.UserService; import com.opensymphony.xwork2.ActionSupport; @Controller("user") @Scope("prototype") public class UserAction extends ActionSupport { @Resource private UserService userService; private User user; private String id; private List<User> list; /** * */ private static final long serialVersionUID = 5638432269244791021L; /*业务方法*/ public String login()throws Exception { User currUser = userService.login(user); if(currUser != null) { HttpSession session = ServletActionContext.getRequest().getSession(); session.setAttribute("currUser", currUser); return list(); } else { return "input"; } } public String list()throws Exception { list = userService.findAll(); return "list"; } public String add()throws Exception { userService.save(user); return "reload";//list(); } public String delete()throws Exception { userService.delete(id); return "reload"; } public String update()throws Exception { userService.update(user); return "reload"; } public String toUpdate()throws Exception { user = userService.get(id); return "input"; } /*geterAndSeter*/ public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<User> getList() { return list; } public void setList(List<User> list) { this.list = list; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
列表页面list.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>列表页面</title> </head> <body> <a href="<%=basePath %>/user/add.jsp">添加用户</a> <table border="1" width="60%"> <tr> <td>用户名</td> <td>是否可用</td> <td>操作</td> </tr> <c:forEach items="${list}" var="u"> <tr> <td>${u.name }</td> <td>${u.enable }</td> <td> <a href="<%=basePath %>/user_delete.action?id=${u.id }">删除</a> <a href="<%=basePath %>/user_toUpdate.action?id=${u.id }">修改</a> </td> </tr> </c:forEach> </table> </body> </html>结束!