Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合--(转)

最新版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

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  7.   <display-name></display-name>   
  8.     
  9.   <!-- 添加对spring的支持 -->  
  10.   <context-param>  
  11.     <param-name>contextConfigLocation</param-name>  
  12.     <param-value>classpath:applicationContext.xml</param-value>  
  13.   </context-param>  
  14.     
  15.     <listener>  
  16.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  17.     </listener>  
  18.       
  19.   <!-- 添加对struts2的支持 -->  
  20.   <filter>  
  21.     <filter-name>struts2</filter-name>  
  22.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  23.   </filter>   
  24.   <!-- 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后,  
  25.      hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误,  
  26.       这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态  
  27.       知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 -->  
  28.    <filter>  
  29.     <filter-name>openSessionInViewFilter</filter-name>  
  30.     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
  31.     <init-param>  
  32.       <param-name>singleSession</param-name>  
  33.       <param-value>true</param-value>  
  34.     </init-param>  
  35.   </filter>  
  36.     
  37.   <filter-mapping>  
  38.     <filter-name>struts2</filter-name>  
  39.     <url-pattern>/*</url-pattern>  
  40.   </filter-mapping>  
  41.    <filter-mapping>  
  42.     <filter-name>openSessionInViewFilter</filter-name>  
  43.     <url-pattern>*.do,*.action</url-pattern>  
  44.   </filter-mapping>  
  45.     
  46.   <welcome-file-list>  
  47.     <welcome-file>index.jsp</welcome-file>  
  48.   </welcome-file-list>  
  49. </web-app>  

2. applicationContext.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:context="http://www.springframework.org/schema/context"  
  7.     xmlns:jee="http://www.springframework.org/schema/jee"  
  8.     xmlns:tx="http://www.springframework.org/schema/tx"  
  9.     xsi:schemaLocation="    
  10.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  11.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  12.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  13.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
  14.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    
  15.   
  16.     <!-- 加载数据库属性配置文件 -->  
  17.     <context:property-placeholder location="classpath:db.properties" />  
  18.   
  19.     <!-- 数据库连接池c3p0配置 -->  
  20.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  21.         destroy-method="close">  
  22.         <property name="jdbcUrl" value="${db.url}"></property>  
  23.         <property name="driverClass" value="${db.driverClassName}"></property>  
  24.         <property name="user" value="${db.username}"></property>  
  25.         <property name="password" value="${db.password}"></property>  
  26.         <property name="maxPoolSize" value="40"></property>  
  27.         <property name="minPoolSize" value="1"></property>  
  28.         <property name="initialPoolSize" value="1"></property>  
  29.         <property name="maxIdleTime" value="20"></property>  
  30.     </bean>  
  31.       
  32.     <!-- session工厂 -->  
  33.     <bean id="sessionFactory"  
  34.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  35.         <property name="dataSource">  
  36.             <ref bean="dataSource" />  
  37.         </property>  
  38.         <property name="configLocation" value="classpath:hibernate.cfg.xml"/>  
  39.         <!-- 自动扫描注解方式配置的hibernate类文件 -->  
  40.         <property name="packagesToScan">  
  41.             <list>  
  42.                 <value>com.bufoon.entity</value>  
  43.             </list>  
  44.         </property>  
  45.     </bean>  
  46.   
  47.     <!-- 配置事务管理器 -->  
  48.     <bean id="transactionManager"  
  49.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  50.         <property name="sessionFactory" ref="sessionFactory" />  
  51.     </bean>  
  52.   
  53.     <!-- 配置事务通知属性 -->  
  54.     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  55.         <!-- 定义事务传播属性 -->  
  56.         <tx:attributes>  
  57.             <tx:method name="insert*" propagation="REQUIRED" />  
  58.             <tx:method name="update*" propagation="REQUIRED" />  
  59.             <tx:method name="edit*" propagation="REQUIRED" />  
  60.             <tx:method name="save*" propagation="REQUIRED" />  
  61.             <tx:method name="add*" propagation="REQUIRED" />  
  62.             <tx:method name="new*" propagation="REQUIRED" />  
  63.             <tx:method name="set*" propagation="REQUIRED" />  
  64.             <tx:method name="remove*" propagation="REQUIRED" />  
  65.             <tx:method name="delete*" propagation="REQUIRED" />  
  66.             <tx:method name="change*" propagation="REQUIRED" />  
  67.             <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
  68.             <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
  69.             <tx:method name="load*" propagation="REQUIRED" read-only="true" />  
  70.             <tx:method name="*" propagation="REQUIRED" read-only="true" />  
  71.         </tx:attributes>  
  72.     </tx:advice>  
  73.       
  74.     <!-- 应用普通类获取bean    
  75.     <bean id="appContext" class="com.soanl.util.tool.ApplicationUtil"/>-->  
  76.   
  77.     <!-- 配置事务切面 -->  
  78.     <aop:config>  
  79.         <aop:pointcut id="serviceOperation"  
  80.             expression="execution(* com.bufoon.service..*.*(..))" />  
  81.         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
  82.     </aop:config>  
  83.   
  84.     <!-- 自动加载构建bean -->  
  85.     <context:component-scan base-package="com.bufoon" />  
  86.   
  87. </beans>  

3. db.properties

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. db.driverClassName=com.mysql.jdbc.Driver  
  2. db.url=jdbc:mysql://localhost:3306/test  
  3. db.username=root  
  4. db.password=root  

4. hibernate.cfg.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.     <session-factory>  
  8.   
  9.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  10.         <property name="jdbc.batch_size">20</property>  
  11.         <property name="connection.autocommit">true</property>  
  12.   
  13.         <!-- 显示sql语句 -->  
  14.         <property name="show_sql">true</property>  
  15.         <property name="connection.useUnicode">true</property>  
  16.         <property name="connection.characterEncoding">UTF-8</property>  
  17.   
  18.         <!-- 缓存设置 -->  
  19.         <property name="cache.provider_configuration_file_resource_path">/ehcache.xml</property>  
  20.         <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  
  21.         <property name="cache.use_query_cache">true</property>  
  22.   
  23.     </session-factory>  
  24. </hibernate-configuration>  

5. struts.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5.       
  6. <struts>  
  7.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  8.     <constant name="struts.action.extension" value="action" />  
  9.     <constant name="struts.serve.static.browserCache" value="false" />  
  10.       
  11.     <package name="s2sh" namespace="/user" extends="struts-default">  
  12.         <action name="login" method="login" class="com.bufoon.action.LoginAction">  
  13.             <result name="success">/success.jsp</result>  
  14.             <result name="error">/login.jsp</result>  
  15.         </action>  
  16.     </package>  
  17.       
  18. </struts>   


6. ehcache.xml (可以到下载的hibernate文件目录(hibernate-release-4.3.4.Final\hibernate-release-4.3.4.Final\project\etc)下找

五. JAVA类

1.BaseDAO.java(网上找的一个)

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. /** 
  7.  * 基础数据库操作类 
  8.  *  
  9.  * @author ss 
  10.  *  
  11.  */  
  12. public interface BaseDAO<T> {  
  13.   
  14.     /** 
  15.      * 保存一个对象 
  16.      *  
  17.      * @param o 
  18.      * @return 
  19.      */  
  20.     public Serializable save(T o);  
  21.   
  22.     /** 
  23.      * 删除一个对象 
  24.      *  
  25.      * @param o 
  26.      */  
  27.     public void delete(T o);  
  28.   
  29.     /** 
  30.      * 更新一个对象 
  31.      *  
  32.      * @param o 
  33.      */  
  34.     public void update(T o);  
  35.   
  36.     /** 
  37.      * 保存或更新对象 
  38.      *  
  39.      * @param o 
  40.      */  
  41.     public void saveOrUpdate(T o);  
  42.   
  43.     /** 
  44.      * 查询 
  45.      *  
  46.      * @param hql 
  47.      * @return 
  48.      */  
  49.     public List<T> find(String hql);  
  50.   
  51.     /** 
  52.      * 查询集合 
  53.      *  
  54.      * @param hql 
  55.      * @param param 
  56.      * @return 
  57.      */  
  58.     public List<T> find(String hql, Object[] param);  
  59.   
  60.     /** 
  61.      * 查询集合 
  62.      *  
  63.      * @param hql 
  64.      * @param param 
  65.      * @return 
  66.      */  
  67.     public List<T> find(String hql, List<Object> param);  
  68.   
  69.     /** 
  70.      * 查询集合(带分页) 
  71.      *  
  72.      * @param hql 
  73.      * @param param 
  74.      * @param page 
  75.      *            查询第几页 
  76.      * @param rows 
  77.      *            每页显示几条记录 
  78.      * @return 
  79.      */  
  80.     public List<T> find(String hql, Object[] param, Integer page, Integer rows);  
  81.   
  82.     /** 
  83.      * 查询集合(带分页) 
  84.      *  
  85.      * @param hql 
  86.      * @param param 
  87.      * @param page 
  88.      * @param rows 
  89.      * @return 
  90.      */  
  91.     public List<T> find(String hql, List<Object> param, Integer page, Integer rows);  
  92.   
  93.     /** 
  94.      * 获得一个对象 
  95.      *  
  96.      * @param c 
  97.      *            对象类型 
  98.      * @param id 
  99.      * @return Object 
  100.      */  
  101.     public T get(Class<T> c, Serializable id);  
  102.   
  103.     /** 
  104.      * 获得一个对象 
  105.      *  
  106.      * @param hql 
  107.      * @param param 
  108.      * @return Object 
  109.      */  
  110.     public T get(String hql, Object[] param);  
  111.   
  112.     /** 
  113.      * 获得一个对象 
  114.      *  
  115.      * @param hql 
  116.      * @param param 
  117.      * @return 
  118.      */  
  119.     public T get(String hql, List<Object> param);  
  120.   
  121.     /** 
  122.      * select count(*) from 类 
  123.      *  
  124.      * @param hql 
  125.      * @return 
  126.      */  
  127.     public Long count(String hql);  
  128.   
  129.     /** 
  130.      * select count(*) from 类 
  131.      *  
  132.      * @param hql 
  133.      * @param param 
  134.      * @return 
  135.      */  
  136.     public Long count(String hql, Object[] param);  
  137.   
  138.     /** 
  139.      * select count(*) from 类 
  140.      *  
  141.      * @param hql 
  142.      * @param param 
  143.      * @return 
  144.      */  
  145.     public Long count(String hql, List<Object> param);  
  146.   
  147.     /** 
  148.      * 执行HQL语句 
  149.      *  
  150.      * @param hql 
  151.      * @return 响应数目 
  152.      */  
  153.     public Integer executeHql(String hql);  
  154.   
  155.     /** 
  156.      * 执行HQL语句 
  157.      *  
  158.      * @param hql 
  159.      * @param param 
  160.      * @return 响应数目 
  161.      */  
  162.     public Integer executeHql(String hql, Object[] param);  
  163.   
  164.     /** 
  165.      * 执行HQL语句 
  166.      *  
  167.      * @param hql 
  168.      * @param param 
  169.      * @return 
  170.      */  
  171.     public Integer executeHql(String hql, List<Object> param);  
  172.   
  173. }  

2. BaseDAOImpl.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.dao.impl;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import org.hibernate.Query;  
  7. import org.hibernate.Session;  
  8. import org.hibernate.SessionFactory;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.stereotype.Repository;  
  11.   
  12. import com.bufoon.dao.BaseDAO;  
  13.   
  14. @Repository("baseDAO")  
  15. @SuppressWarnings("all")  
  16. public class BaseDAOImpl<T> implements BaseDAO<T> {  
  17.   
  18.     private SessionFactory sessionFactory;  
  19.   
  20.     public SessionFactory getSessionFactory() {  
  21.         return sessionFactory;  
  22.     }  
  23.   
  24.     @Autowired  
  25.     public void setSessionFactory(SessionFactory sessionFactory) {  
  26.         this.sessionFactory = sessionFactory;  
  27.     }  
  28.   
  29.     private Session getCurrentSession() {  
  30.         return sessionFactory.getCurrentSession();  
  31.     }  
  32.   
  33.     public Serializable save(T o) {  
  34.         return this.getCurrentSession().save(o);  
  35.     }  
  36.   
  37.     public void delete(T o) {  
  38.         this.getCurrentSession().delete(o);  
  39.     }  
  40.   
  41.     public void update(T o) {  
  42.         this.getCurrentSession().update(o);  
  43.     }  
  44.   
  45.     public void saveOrUpdate(T o) {  
  46.         this.getCurrentSession().saveOrUpdate(o);  
  47.     }  
  48.   
  49.     public List<T> find(String hql) {  
  50.         return this.getCurrentSession().createQuery(hql).list();  
  51.     }  
  52.   
  53.     public List<T> find(String hql, Object[] param) {  
  54.         Query q = this.getCurrentSession().createQuery(hql);  
  55.         if (param != null && param.length > 0) {  
  56.             for (int i = 0; i < param.length; i++) {  
  57.                 q.setParameter(i, param[i]);  
  58.             }  
  59.         }  
  60.         return q.list();  
  61.     }  
  62.   
  63.     public List<T> find(String hql, List<Object> param) {  
  64.         Query q = this.getCurrentSession().createQuery(hql);  
  65.         if (param != null && param.size() > 0) {  
  66.             for (int i = 0; i < param.size(); i++) {  
  67.                 q.setParameter(i, param.get(i));  
  68.             }  
  69.         }  
  70.         return q.list();  
  71.     }  
  72.   
  73.     public List<T> find(String hql, Object[] param, Integer page, Integer rows) {  
  74.         if (page == null || page < 1) {  
  75.             page = 1;  
  76.         }  
  77.         if (rows == null || rows < 1) {  
  78.             rows = 10;  
  79.         }  
  80.         Query q = this.getCurrentSession().createQuery(hql);  
  81.         if (param != null && param.length > 0) {  
  82.             for (int i = 0; i < param.length; i++) {  
  83.                 q.setParameter(i, param[i]);  
  84.             }  
  85.         }  
  86.         return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();  
  87.     }  
  88.   
  89.     public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {  
  90.         if (page == null || page < 1) {  
  91.             page = 1;  
  92.         }  
  93.         if (rows == null || rows < 1) {  
  94.             rows = 10;  
  95.         }  
  96.         Query q = this.getCurrentSession().createQuery(hql);  
  97.         if (param != null && param.size() > 0) {  
  98.             for (int i = 0; i < param.size(); i++) {  
  99.                 q.setParameter(i, param.get(i));  
  100.             }  
  101.         }  
  102.         return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();  
  103.     }  
  104.   
  105.     public T get(Class<T> c, Serializable id) {  
  106.         return (T) this.getCurrentSession().get(c, id);  
  107.     }  
  108.   
  109.     public T get(String hql, Object[] param) {  
  110.         List<T> l = this.find(hql, param);  
  111.         if (l != null && l.size() > 0) {  
  112.             return l.get(0);  
  113.         } else {  
  114.             return null;  
  115.         }  
  116.     }  
  117.   
  118.     public T get(String hql, List<Object> param) {  
  119.         List<T> l = this.find(hql, param);  
  120.         if (l != null && l.size() > 0) {  
  121.             return l.get(0);  
  122.         } else {  
  123.             return null;  
  124.         }  
  125.     }  
  126.   
  127.     public Long count(String hql) {  
  128.         return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();  
  129.     }  
  130.   
  131.     public Long count(String hql, Object[] param) {  
  132.         Query q = this.getCurrentSession().createQuery(hql);  
  133.         if (param != null && param.length > 0) {  
  134.             for (int i = 0; i < param.length; i++) {  
  135.                 q.setParameter(i, param[i]);  
  136.             }  
  137.         }  
  138.         return (Long) q.uniqueResult();  
  139.     }  
  140.   
  141.     public Long count(String hql, List<Object> param) {  
  142.         Query q = this.getCurrentSession().createQuery(hql);  
  143.         if (param != null && param.size() > 0) {  
  144.             for (int i = 0; i < param.size(); i++) {  
  145.                 q.setParameter(i, param.get(i));  
  146.             }  
  147.         }  
  148.         return (Long) q.uniqueResult();  
  149.     }  
  150.   
  151.     public Integer executeHql(String hql) {  
  152.         return this.getCurrentSession().createQuery(hql).executeUpdate();  
  153.     }  
  154.   
  155.     public Integer executeHql(String hql, Object[] param) {  
  156.         Query q = this.getCurrentSession().createQuery(hql);  
  157.         if (param != null && param.length > 0) {  
  158.             for (int i = 0; i < param.length; i++) {  
  159.                 q.setParameter(i, param[i]);  
  160.             }  
  161.         }  
  162.         return q.executeUpdate();  
  163.     }  
  164.   
  165.     public Integer executeHql(String hql, List<Object> param) {  
  166.         Query q = this.getCurrentSession().createQuery(hql);  
  167.         if (param != null && param.size() > 0) {  
  168.             for (int i = 0; i < param.size(); i++) {  
  169.                 q.setParameter(i, param.get(i));  
  170.             }  
  171.         }  
  172.         return q.executeUpdate();  
  173.     }  
  174.   
  175. }  


3. UserService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.service.user;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.bufoon.entity.User;  
  6.   
  7. public interface UserService {  
  8.   
  9.     public void saveUser(User user);  
  10.       
  11.     public void updateUser(User user);  
  12.       
  13.     public User findUserById(int id);  
  14.       
  15.     public void deleteUser(User user);  
  16.       
  17.     public List<User> findAllList();  
  18.       
  19.     public User findUserByNameAndPassword(String username, String password);  
  20. }  

4. UserServiceImpl.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.service.user.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.stereotype.Service;  
  8.   
  9. import com.bufoon.dao.BaseDAO;  
  10. import com.bufoon.entity.User;  
  11. import com.bufoon.service.user.UserService;  
  12.   
  13. @Service("userService")  
  14. public class UserServiceImpl implements UserService {  
  15.       
  16.     @Resource  
  17.     private BaseDAO<User> baseDAO;  
  18.   
  19.     @Override  
  20.     public void saveUser(User user) {  
  21.         baseDAO.save(user);  
  22.     }  
  23.   
  24.     @Override  
  25.     public void updateUser(User user) {  
  26.         baseDAO.update(user);  
  27.     }  
  28.   
  29.     @Override  
  30.     public User findUserById(int id) {  
  31.         return baseDAO.get(User.class, id);  
  32.     }  
  33.   
  34.     @Override  
  35.     public void deleteUser(User user) {  
  36.         baseDAO.delete(user);  
  37.     }  
  38.   
  39.     @Override  
  40.     public List<User> findAllList() {  
  41.         return baseDAO.find(" from User u order by u.createTime");  
  42.     }  
  43.   
  44.     @Override  
  45.     public User findUserByNameAndPassword(String username, String password) {  
  46.         return baseDAO.get(" from User u where u.userName = ? and u.password = ? "new Object[] { username, password });  
  47.     }  
  48.   
  49. }  

5. LoginAction

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.action;  
  2.   
  3. import javax.annotation.Resource;  
  4. import javax.servlet.http.HttpServletRequest;  
  5.   
  6. import org.apache.struts2.ServletActionContext;  
  7. import org.springframework.stereotype.Controller;  
  8.   
  9. import com.bufoon.entity.User;  
  10. import com.bufoon.service.user.UserService;  
  11. import com.opensymphony.xwork2.ActionSupport;  
  12.   
  13. @Controller  
  14. public class LoginAction extends ActionSupport {  
  15.   
  16.     private static final long serialVersionUID = 1L;  
  17.   
  18.     @Resource  
  19.     private UserService userService;  
  20.       
  21.     private String username;  
  22.     private String password;  
  23.       
  24.     public String login(){  
  25.           
  26.         HttpServletRequest request = ServletActionContext.getRequest();  
  27.         User user = userService.findUserByNameAndPassword(username, password);  
  28.         if (user != null) {  
  29.             request.setAttribute("username", username);  
  30.             return SUCCESS;  
  31.         } else {  
  32.             return ERROR;  
  33.         }  
  34.               
  35.     }  
  36.     public String getUsername() {  
  37.         return username;  
  38.     }  
  39.     public void setUsername(String username) {  
  40.         this.username = username;  
  41.     }  
  42.     public String getPassword() {  
  43.         return password;  
  44.     }  
  45.     public void setPassword(String password) {  
  46.         this.password = password;  
  47.     }  
  48.       
  49. }  

6. Util.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.util;  
  2.   
  3. import java.io.PrintWriter;  
  4. import java.io.StringWriter;  
  5. import java.security.MessageDigest;  
  6.   
  7. import org.springframework.context.ApplicationContext;  
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  9.   
  10. import com.bufoon.entity.User;  
  11. import com.bufoon.service.user.UserService;  
  12.   
  13. import sun.misc.BASE64Encoder;  
  14.   
  15. /** 
  16.  * 通用工具类 
  17.  */  
  18. public class Util {  
  19.   
  20.     /** 
  21.      * 对字符串进行MD5加密 
  22.      *  
  23.      * @param str 
  24.      * @return String 
  25.      */  
  26.     public static String md5Encryption(String str) {  
  27.         String newStr = null;  
  28.         try {  
  29.             MessageDigest md5 = MessageDigest.getInstance("MD5");  
  30.             BASE64Encoder base = new BASE64Encoder();  
  31.             newStr = base.encode(md5.digest(str.getBytes("UTF-8")));  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.         return newStr;  
  36.     }  
  37.       
  38.   
  39.     /** 
  40.      * 判断字符串是否为空 
  41.      *  
  42.      * @param str 
  43.      *            字符串 
  44.      * @return true:为空; false:非空 
  45.      */  
  46.     public static boolean isNull(String str) {  
  47.         if (str != null && !str.trim().equals("")) {  
  48.             return false;  
  49.         } else {  
  50.             return true;  
  51.         }  
  52.     }  
  53. }  
7.User.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bufoon.entity;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.Id;  
  9. import javax.persistence.Temporal;  
  10. import javax.persistence.TemporalType;  
  11.   
  12. import org.hibernate.annotations.GenericGenerator;  
  13. @Entity  
  14. public class User {  
  15.   
  16.     private Integer id;  
  17.     private String userName;  
  18.     private String password;  
  19.     private String address;  
  20.     private String phoneNumber;  
  21.     private Date createTime;  
  22.     private Date updateTime;  
  23.       
  24.     @Id  
  25.     @GenericGenerator(name = "generator", strategy = "increment")  
  26.      @GeneratedValue(generator = "generator")  
  27.     @Column(name = "ID", length=11)  
  28.     public Integer getId() {  
  29.         return id;  
  30.     }  
  31.     public void setId(Integer id) {  
  32.         this.id = id;  
  33.     }  
  34.     @Column(name = "user_name", length = 20)  
  35.     public String getUserName() {  
  36.         return userName;  
  37.     }  
  38.     public void setUserName(String userName) {  
  39.         this.userName = userName;  
  40.     }  
  41.     @Column(name = "password", length = 20)  
  42.     public String getPassword() {  
  43.         return password;  
  44.     }  
  45.     public void setPassword(String password) {  
  46.         this.password = password;  
  47.     }  
  48.     @Column(name = "address", length = 100)  
  49.     public String getAddress() {  
  50.         return address;  
  51.     }  
  52.     public void setAddress(String address) {  
  53.         this.address = address;  
  54.     }  
  55.     @Column(name = "phone_number", length = 20)  
  56.     public String getPhoneNumber() {  
  57.         return phoneNumber;  
  58.     }  
  59.     public void setPhoneNumber(String phoneNumber) {  
  60.         this.phoneNumber = phoneNumber;  
  61.     }  
  62.     @Temporal(TemporalType.TIMESTAMP)  
  63.     @Column(name = "create_time")  
  64.     public Date getCreateTime() {  
  65.         return createTime;  
  66.     }  
  67.     public void setCreateTime(Date createTime) {  
  68.         this.createTime = createTime;  
  69.     }  
  70.     @Temporal(TemporalType.TIMESTAMP)  
  71.     @Column(name = "update_time")  
  72.     public Date getUpdateTime() {  
  73.         return updateTime;  
  74.     }  
  75.     public void setUpdateTime(Date updateTime) {  
  76.         this.updateTime = updateTime;  
  77.     }  
  78.       
  79. }  


六. JSP文件

1. login.jsp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.   <form action="${pageContext.request.contextPath}/user/login.action" method="post">  
  25.      username:<input type="text" name="username"/> <br/>  
  26.      password:<input type="password" name="password"/> <br/>  
  27.     <input type="submit" value="login"/><input type="reset" value="reset"/>  
  28.   </form>  
  29.   </body>  
  30. </html>  

2. success.jsp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.    欢迎您:{username}!  
  25.   </body>  
  26. </html>  

附上下载地址:http://download.csdn.net/detail/soanl/7158959

================================================================ENDING========================================================

2014-03-29

       布丰(bufoon)

更正(struts.xml文件)感谢u013506859提出
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值