最新版Struts2+Hibernate+Spring整合
目前为止三大框架最新版本是:
struts2.3.16.1
hibernate4.3.4
spring4.0.2
其中struts2和hibernate的下载方式比较简单,但是spring下载有点麻烦,可以直接复制下面链接下载最新版spring
![]()
http://repo.springsource.org/libs-release-local/org/springframework/spring/4.0.2.RELEASE/spring-framework-4.0.2.RELEASE-dist.zip
一. 所需的jar包(其中aopaliance-1.0.jar,是spring所依赖的jar,直接复制粘贴到谷歌百度就有的下载)
框架 |
版本 |
所需jar包 |
Struts2 |
2.3.16.1 |
 |
Hibernate |
4.3.4 |
 |
spring |
4.0.2 |
 |
其它 |
无 |
 |
二. 创建一张表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`phone_number` varchar(20) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULTCHARSET=utf8;
并插入一条数据
INSERT INTO `user` VALUES ('1', 'test','test', 'test', 'test', '2014-03-29 00:48:14', '2014-03-29 00:48:17');
三. 先看下myeclipse的目录结构

四. 配置文件
1. web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- 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_3_0.xsd">
- <display-name></display-name>
-
-
- <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>
-
-
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <!-- 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后,
- hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误,
- 这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态
- 知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 -->
- <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>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>*.do,*.action</url-pattern>
- </filter-mapping>
-
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
2. 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:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:jee="http://www.springframework.org/schema/jee"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
-
-
- <context:property-placeholder location="classpath:db.properties" />
-
-
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
- destroy-method="close">
- <property name="jdbcUrl" value="${db.url}"></property>
- <property name="driverClass" value="${db.driverClassName}"></property>
- <property name="user" value="${db.username}"></property>
- <property name="password" value="${db.password}"></property>
- <property name="maxPoolSize" value="40"></property>
- <property name="minPoolSize" value="1"></property>
- <property name="initialPoolSize" value="1"></property>
- <property name="maxIdleTime" value="20"></property>
- </bean>
-
-
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <property name="dataSource">
- <ref bean="dataSource" />
- </property>
- <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
-
- <property name="packagesToScan">
- <list>
- <value>com.bufoon.entity</value>
- </list>
- </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="insert*" propagation="REQUIRED" />
- <tx:method name="update*" propagation="REQUIRED" />
- <tx:method name="edit*" propagation="REQUIRED" />
- <tx:method name="save*" propagation="REQUIRED" />
- <tx:method name="add*" propagation="REQUIRED" />
- <tx:method name="new*" propagation="REQUIRED" />
- <tx:method name="set*" propagation="REQUIRED" />
- <tx:method name="remove*" propagation="REQUIRED" />
- <tx:method name="delete*" propagation="REQUIRED" />
- <tx:method name="change*" propagation="REQUIRED" />
- <tx:method name="get*" propagation="REQUIRED" read-only="true" />
- <tx:method name="find*" propagation="REQUIRED" read-only="true" />
- <tx:method name="load*" propagation="REQUIRED" read-only="true" />
- <tx:method name="*" propagation="REQUIRED" read-only="true" />
- </tx:attributes>
- </tx:advice>
-
- <!-- 应用普通类获取bean
- <bean id="appContext" class="com.soanl.util.tool.ApplicationUtil"/>-->
-
-
- <aop:config>
- <aop:pointcut id="serviceOperation"
- expression="execution(* com.bufoon.service..*.*(..))" />
- <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
- </aop:config>
-
-
- <context:component-scan base-package="com.bufoon" />
-
- </beans>
3. db.properties
- db.driverClassName=com.mysql.jdbc.Driver
- db.url=jdbc:mysql://localhost:3306/test
- db.username=root
- db.password=root
4. hibernate.cfg.xml
- <?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="jdbc.batch_size">20</property>
- <property name="connection.autocommit">true</property>
-
-
- <property name="show_sql">true</property>
- <property name="connection.useUnicode">true</property>
- <property name="connection.characterEncoding">UTF-8</property>
-
-
- <property name="cache.provider_configuration_file_resource_path">/ehcache.xml</property>
- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
- <property name="cache.use_query_cache">true</property>
-
- </session-factory>
- </hibernate-configuration>
5. struts.xml
- <?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="jdbc.batch_size">20</property>
- <property name="connection.autocommit">true</property>
-
-
- <property name="show_sql">true</property>
- <property name="connection.useUnicode">true</property>
- <property name="connection.characterEncoding">UTF-8</property>
-
-
- <property name="cache.provider_configuration_file_resource_path">/ehcache.xml</property>
- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
- <property name="cache.use_query_cache">true</property>
-
- </session-factory>
- </hibernate-configuration>
6. ehcache.xml (可以到下载的hibernate文件目录(hibernate-release-4.3.4.Final\hibernate-release-4.3.4.Final\project\etc)下找
五. JAVA类
1.BaseDAO.java(网上找的一个)
- package com.bufoon.dao;
-
- import java.io.Serializable;
- import java.util.List;
-
-
-
-
-
-
-
- public interface BaseDAO<T> {
-
-
-
-
-
-
-
- public Serializable save(T o);
-
-
-
-
-
-
- public void delete(T o);
-
-
-
-
-
-
- public void update(T o);
-
-
-
-
-
-
- public void saveOrUpdate(T o);
-
-
-
-
-
-
-
- public List<T> find(String hql);
-
-
-
-
-
-
-
-
- public List<T> find(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public List<T> find(String hql, List<Object> param);
-
-
-
-
-
-
-
-
-
-
-
-
- public List<T> find(String hql, Object[] param, Integer page, Integer rows);
-
-
-
-
-
-
-
-
-
-
- public List<T> find(String hql, List<Object> param, Integer page, Integer rows);
-
-
-
-
-
-
-
-
-
- public T get(Class<T> c, Serializable id);
-
-
-
-
-
-
-
-
- public T get(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public T get(String hql, List<Object> param);
-
-
-
-
-
-
-
- public Long count(String hql);
-
-
-
-
-
-
-
-
- public Long count(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public Long count(String hql, List<Object> param);
-
-
-
-
-
-
-
- public Integer executeHql(String hql);
-
-
-
-
-
-
-
-
- public Integer executeHql(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public Integer executeHql(String hql, List<Object> param);
-
- }
2. BaseDAOImpl.java
- package com.bufoon.dao;
-
- import java.io.Serializable;
- import java.util.List;
-
-
-
-
-
-
-
- public interface BaseDAO<T> {
-
-
-
-
-
-
-
- public Serializable save(T o);
-
-
-
-
-
-
- public void delete(T o);
-
-
-
-
-
-
- public void update(T o);
-
-
-
-
-
-
- public void saveOrUpdate(T o);
-
-
-
-
-
-
-
- public List<T> find(String hql);
-
-
-
-
-
-
-
-
- public List<T> find(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public List<T> find(String hql, List<Object> param);
-
-
-
-
-
-
-
-
-
-
-
-
- public List<T> find(String hql, Object[] param, Integer page, Integer rows);
-
-
-
-
-
-
-
-
-
-
- public List<T> find(String hql, List<Object> param, Integer page, Integer rows);
-
-
-
-
-
-
-
-
-
- public T get(Class<T> c, Serializable id);
-
-
-
-
-
-
-
-
- public T get(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public T get(String hql, List<Object> param);
-
-
-
-
-
-
-
- public Long count(String hql);
-
-
-
-
-
-
-
-
- public Long count(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public Long count(String hql, List<Object> param);
-
-
-
-
-
-
-
- public Integer executeHql(String hql);
-
-
-
-
-
-
-
-
- public Integer executeHql(String hql, Object[] param);
-
-
-
-
-
-
-
-
- public Integer executeHql(String hql, List<Object> param);
-
- }
3. UserService.java
- package com.bufoon.service.user;
-
- import java.util.List;
-
- import com.bufoon.entity.User;
-
- public interface UserService {
-
- public void saveUser(User user);
-
- public void updateUser(User user);
-
- public User findUserById(int id);
-
- public void deleteUser(User user);
-
- public List<User> findAllList();
-
- public User findUserByNameAndPassword(String username, String password);
- }
4. UserServiceImpl.java
- package com.bufoon.service.user.impl;
-
- import java.util.List;
-
- import javax.annotation.Resource;
-
- import org.springframework.stereotype.Service;
-
- import com.bufoon.dao.BaseDAO;
- import com.bufoon.entity.User;
- import com.bufoon.service.user.UserService;
-
- @Service("userService")
- public class UserServiceImpl implements UserService {
-
- @Resource
- private BaseDAO<User> baseDAO;
-
- @Override
- public void saveUser(User user) {
- baseDAO.save(user);
- }
-
- @Override
- public void updateUser(User user) {
- baseDAO.update(user);
- }
-
- @Override
- public User findUserById(int id) {
- return baseDAO.get(User.class, id);
- }
-
- @Override
- public void deleteUser(User user) {
- baseDAO.delete(user);
- }
-
- @Override
- public List<User> findAllList() {
- return baseDAO.find(" from User u order by u.createTime");
- }
-
- @Override
- public User findUserByNameAndPassword(String username, String password) {
- return baseDAO.get(" from User u where u.userName = ? and u.password = ? ", new Object[] { username, password });
- }
-
- }
5. LoginAction
- package com.bufoon.action;
-
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
-
- import org.apache.struts2.ServletActionContext;
- import org.springframework.stereotype.Controller;
-
- import com.bufoon.entity.User;
- import com.bufoon.service.user.UserService;
- import com.opensymphony.xwork2.ActionSupport;
-
- @Controller
- public class LoginAction extends ActionSupport {
-
- private static final long serialVersionUID = 1L;
-
- @Resource
- private UserService userService;
-
- private String username;
- private String password;
-
- public String login(){
-
- HttpServletRequest request = ServletActionContext.getRequest();
- User user = userService.findUserByNameAndPassword(username, password);
- if (user != null) {
- request.setAttribute("username", username);
- return SUCCESS;
- } else {
- return ERROR;
- }
-
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
-
- }
6. Util.java
- package com.bufoon.util;
-
- import java.io.PrintWriter;
- import java.io.StringWriter;
- import java.security.MessageDigest;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import com.bufoon.entity.User;
- import com.bufoon.service.user.UserService;
-
- import sun.misc.BASE64Encoder;
-
-
-
-
- public class Util {
-
-
-
-
-
-
-
- public static String md5Encryption(String str) {
- String newStr = null;
- try {
- MessageDigest md5 = MessageDigest.getInstance("MD5");
- BASE64Encoder base = new BASE64Encoder();
- newStr = base.encode(md5.digest(str.getBytes("UTF-8")));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return newStr;
- }
-
-
-
-
-
-
-
-
-
- public static boolean isNull(String str) {
- if (str != null && !str.trim().equals("")) {
- return false;
- } else {
- return true;
- }
- }
- }
六. JSP文件
1. login.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- 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>
- <base href="<%=basePath%>">
-
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- </head>
-
- <body>
- <form action="${pageContext.request.contextPath}/user/login.action" method="post">
- username:<input type="text" name="username"/> <br/>
- password:<input type="password" name="password"/> <br/>
- <input type="submit" value="login"/><input type="reset" value="reset"/>
- </form>
- </body>
- </html>
2. success.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- 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>
- <base href="<%=basePath%>">
-
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- </head>
-
- <body>
- <form action="${pageContext.request.contextPath}/user/login.action" method="post">
- username:<input type="text" name="username"/> <br/>
- password:<input type="password" name="password"/> <br/>
- <input type="submit" value="login"/><input type="reset" value="reset"/>
- </form>
- </body>
- </html>
================================================================ENDING==================================================