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 

  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.   <!– 添加对spring的支持 –>
  9.   <context-param>
  10.     <param-name>contextConfigLocation</param-name>
  11.     <param-value>classpath:applicationContext.xml</param-value>
  12.   </context-param>
  13.     <listener>
  14.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  15.     </listener>
  16.   <!– 添加对struts2的支持 –>
  17.   <filter>
  18.     <filter-name>struts2</filter-name>
  19.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  20.   </filter>
  21.   <!– 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后,
  22.      hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误,
  23.       这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态
  24.       知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 –>
  25.    <filter>
  26.     <filter-name>openSessionInViewFilter</filter-name>
  27.     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  28.     <init-param>
  29.       <param-name>singleSession</param-name>
  30.       <param-value>true</param-value>
  31.     </init-param>
  32.   </filter>
  33.   <filter-mapping>
  34.     <filter-name>struts2</filter-name>
  35.     <url-pattern>/*</url-pattern>
  36.   </filter-mapping>
  37.    <filter-mapping>
  38.     <filter-name>openSessionInViewFilter</filter-name>
  39.     <url-pattern>*.do,*.action</url-pattern>
  40.   </filter-mapping>
  41.   <welcome-file-list>
  42.     <welcome-file>index.jsp</welcome-file>
  43.   </welcome-file-list>
  44. </web-app>

2. applicationContext.xml 

 

  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.     <context:property-placeholder location=”classpath:db.properties” />
  17.     <!– 数据库连接池c3p0配置 –>
  18.     <bean id=”dataSource” class=”com.mchange.v2.c3p0.ComboPooledDataSource”
  19.         destroy-method=”close”>
  20.         <property name=”jdbcUrl” value=”${db.url}”></property>
  21.         <property name=”driverClass” value=”${db.driverClassName}”></property>
  22.         <property name=”user” value=”${db.username}”></property>
  23.         <property name=”password” value=”${db.password}”></property>
  24.         <property name=”maxPoolSize” value=”40″></property>
  25.         <property name=”minPoolSize” value=”1″></property>
  26.         <property name=”initialPoolSize” value=”1″></property>
  27.         <property name=”maxIdleTime” value=”20″></property>
  28.     </bean>
  29.     <!– session工厂 –>
  30.     <bean id=”sessionFactory”
  31.         class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
  32.         <property name=”dataSource”>
  33.             <ref bean=”dataSource” />
  34.         </property>
  35.         <property name=”configLocation” value=”classpath:hibernate.cfg.xml”/>
  36.         <!– 自动扫描注解方式配置的hibernate类文件 –>
  37.         <property name=”packagesToScan”>
  38.             <list>
  39.                 <value>com.bufoon.entity</value>
  40.             </list>
  41.         </property>
  42.     </bean>
  43.     <!– 配置事务管理器 –>
  44.     <bean id=”transactionManager”
  45.         class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
  46.         <property name=”sessionFactory” ref=”sessionFactory” />
  47.     </bean>
  48.     <!– 配置事务通知属性 –>
  49.     <tx:advice id=”txAdvice” transaction-manager=”transactionManager”>
  50.         <!– 定义事务传播属性 –>
  51.         <tx:attributes>
  52.             <tx:method name=”insert*” propagation=”REQUIRED” />
  53.             <tx:method name=”update*” propagation=”REQUIRED” />
  54.             <tx:method name=”edit*” propagation=”REQUIRED” />
  55.             <tx:method name=”save*” propagation=”REQUIRED” />
  56.             <tx:method name=”add*” propagation=”REQUIRED” />
  57.             <tx:method name=”new*” propagation=”REQUIRED” />
  58.             <tx:method name=”set*” propagation=”REQUIRED” />
  59.             <tx:method name=”remove*” propagation=”REQUIRED” />
  60.             <tx:method name=”delete*” propagation=”REQUIRED” />
  61.             <tx:method name=”change*” propagation=”REQUIRED” />
  62.             <tx:method name=”get*” propagation=”REQUIRED” read-only=”true” />
  63.             <tx:method name=”find*” propagation=”REQUIRED” read-only=”true” />
  64.             <tx:method name=”load*” propagation=”REQUIRED” read-only=”true” />
  65.             <tx:method name=”*” propagation=”REQUIRED” read-only=”true” />
  66.         </tx:attributes>
  67.     </tx:advice>
  68.     <!– 应用普通类获取bean
  69.     <bean id=”appContext” class=”com.soanl.util.tool.ApplicationUtil”/>–>
  70.     <!– 配置事务切面 –>
  71.     <aop:config>
  72.         <aop:pointcut id=”serviceOperation”
  73.             expression=”execution(* com.bufoon.service..*.*(..))” />
  74.         <aop:advisor advice-ref=”txAdvice” pointcut-ref=”serviceOperation” />
  75.     </aop:config>
  76.     <!– 自动加载构建bean –>
  77.     <context:component-scan base-package=”com.bufoon” />
  78. </beans>

3. db.properties 

 

  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 

 

  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. <hibernate-configuration>
  6.     <session-factory>
  7.         <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
  8.         <property name=”jdbc.batch_size”>20</property>
  9.         <property name=”connection.autocommit”>true</property>
  10.         <!– 显示sql语句 –>
  11.         <property name=”show_sql”>true</property>
  12.         <property name=”connection.useUnicode”>true</property>
  13.         <property name=”connection.characterEncoding”>UTF-8</property>
  14.         <!– 缓存设置 –>
  15.         <property name=”cache.provider_configuration_file_resource_path”>/ehcache.xml</property>
  16.         <property name=”hibernate.cache.region.factory_class”>org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  17.         <property name=”cache.use_query_cache”>true</property>
  18.     </session-factory>
  19. </hibernate-configuration>

5. struts.xml 

 

  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. <struts>
  6.     <constant name=”struts.i18n.encoding” value=”UTF-8″ />
  7.     <constant name=”struts.action.extension” value=”action” />
  8.     <constant name=”struts.serve.static.browserCache” value=”false” />
  9.     <package name=”s2sh” namespace=”/user” extends=”struts-default”>
  10.         <action name=”login” method=”login” class=”com.bufoon.action.LoginAction”>
  11.             <result name=”success”>/success.jsp</result>
  12.             <result name=”error”>/login.jsp</result>
  13.         </action>
  14.     </package>
  15. </struts>

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

五. JAVA类

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

 

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

2. BaseDAOImpl.java 

 

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

 

3. UserService.java 

 

  1. package com.bufoon.service.user;
  2. import java.util.List;
  3. import com.bufoon.entity.User;
  4. public interface UserService {
  5.     public void saveUser(User user);
  6.     public void updateUser(User user);
  7.     public User findUserById(int id);
  8.     public void deleteUser(User user);
  9.     public List<User> findAllList();
  10.     public User findUserByNameAndPassword(String username, String password);
  11. }

4. UserServiceImpl.java 

 

  1. package com.bufoon.service.user.impl;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.springframework.stereotype.Service;
  5. import com.bufoon.dao.BaseDAO;
  6. import com.bufoon.entity.User;
  7. import com.bufoon.service.user.UserService;
  8. @Service(“userService”)
  9. public class UserServiceImpl implements UserService {
  10.     @Resource
  11.     private BaseDAO<User> baseDAO;
  12.     @Override
  13.     public void saveUser(User user) {
  14.         baseDAO.save(user);
  15.     }
  16.     @Override
  17.     public void updateUser(User user) {
  18.         baseDAO.update(user);
  19.     }
  20.     @Override
  21.     public User findUserById(int id) {
  22.         return baseDAO.get(User.class, id);
  23.     }
  24.     @Override
  25.     public void deleteUser(User user) {
  26.         baseDAO.delete(user);
  27.     }
  28.     @Override
  29.     public List<User> findAllList() {
  30.         return baseDAO.find(“ from User u order by u.createTime”);
  31.     }
  32.     @Override
  33.     public User findUserByNameAndPassword(String username, String password) {
  34.         return baseDAO.get(“ from User u where u.userName = ? and u.password = ? ”, new Object[] { username, password });
  35.     }
  36. }

5. LoginAction 

 

  1. package com.bufoon.action;
  2. import javax.annotation.Resource;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.ServletActionContext;
  5. import org.springframework.stereotype.Controller;
  6. import com.bufoon.entity.User;
  7. import com.bufoon.service.user.UserService;
  8. import com.opensymphony.xwork2.ActionSupport;
  9. @Controller
  10. public class LoginAction extends ActionSupport {
  11.     private static final long serialVersionUID = 1L;
  12.     @Resource
  13.     private UserService userService;
  14.     private String username;
  15.     private String password;
  16.     public String login(){
  17.         HttpServletRequest request = ServletActionContext.getRequest();
  18.         User user = userService.findUserByNameAndPassword(username, password);
  19.         if (user != null) {
  20.             request.setAttribute(“username”, username);
  21.             return SUCCESS;
  22.         } else {
  23.             return ERROR;
  24.         }
  25.     }
  26.     public String getUsername() {
  27.         return username;
  28.     }
  29.     public void setUsername(String username) {
  30.         this.username = username;
  31.     }
  32.     public String getPassword() {
  33.         return password;
  34.     }
  35.     public void setPassword(String password) {
  36.         this.password = password;
  37.     }
  38. }

6. Util.java 

 

  1. package com.bufoon.util;
  2. import java.io.PrintWriter;
  3. import java.io.StringWriter;
  4. import java.security.MessageDigest;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7. import com.bufoon.entity.User;
  8. import com.bufoon.service.user.UserService;
  9. import sun.misc.BASE64Encoder;
  10. /**
  11.  * 通用工具类
  12.  */
  13. public class Util {
  14.     /**
  15.      * 对字符串进行MD5加密
  16.      *
  17.      * @param str
  18.      * @return String
  19.      */
  20.     public static String md5Encryption(String str) {
  21.         String newStr = null;
  22.         try {
  23.             MessageDigest md5 = MessageDigest.getInstance(“MD5″);
  24.             BASE64Encoder base = new BASE64Encoder();
  25.             newStr = base.encode(md5.digest(str.getBytes(“UTF-8″)));
  26.         } catch (Exception e) {
  27.             e.printStackTrace();
  28.         }
  29.         return newStr;
  30.     }
  31.     /**
  32.      * 判断字符串是否为空
  33.      *
  34.      * @param str
  35.      *            字符串
  36.      * @return true:为空; false:非空
  37.      */
  38.     public static boolean isNull(String str) {
  39.         if (str != null && !str.trim().equals(“”)) {
  40.             return false;
  41.         } else {
  42.             return true;
  43.         }
  44.     }
  45. }

7.User.java

  1. package com.bufoon.entity;
  2. import java.util.Date;
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.Id;
  7. import javax.persistence.Temporal;
  8. import javax.persistence.TemporalType;
  9. import org.hibernate.annotations.GenericGenerator;
  10. @Entity
  11. public class User {
  12.     private Integer id;
  13.     private String userName;
  14.     private String password;
  15.     private String address;
  16.     private String phoneNumber;
  17.     private Date createTime;
  18.     private Date updateTime;
  19.     @Id
  20.     @GenericGenerator(name = ”generator”, strategy = ”increment”)
  21.      @GeneratedValue(generator = ”generator”)
  22.     @Column(name = ”ID”, length=11)
  23.     public Integer getId() {
  24.         return id;
  25.     }
  26.     public void setId(Integer id) {
  27.         this.id = id;
  28.     }
  29.     @Column(name = ”user_name”, length = 20)
  30.     public String getUserName() {
  31.         return userName;
  32.     }
  33.     public void setUserName(String userName) {
  34.         this.userName = userName;
  35.     }
  36.     @Column(name = ”password”, length = 20)
  37.     public String getPassword() {
  38.         return password;
  39.     }
  40.     public void setPassword(String password) {
  41.         this.password = password;
  42.     }
  43.     @Column(name = ”address”, length = 100)
  44.     public String getAddress() {
  45.         return address;
  46.     }
  47.     public void setAddress(String address) {
  48.         this.address = address;
  49.     }
  50.     @Column(name = ”phone_number”, length = 20)
  51.     public String getPhoneNumber() {
  52.         return phoneNumber;
  53.     }
  54.     public void setPhoneNumber(String phoneNumber) {
  55.         this.phoneNumber = phoneNumber;
  56.     }
  57.     @Temporal(TemporalType.TIMESTAMP)
  58.     @Column(name = ”create_time”)
  59.     public Date getCreateTime() {
  60.         return createTime;
  61.     }
  62.     public void setCreateTime(Date createTime) {
  63.         this.createTime = createTime;
  64.     }
  65.     @Temporal(TemporalType.TIMESTAMP)
  66.     @Column(name = ”update_time”)
  67.     public Date getUpdateTime() {
  68.         return updateTime;
  69.     }
  70.     public void setUpdateTime(Date updateTime) {
  71.         this.updateTime = updateTime;
  72.     }
  73. }

六. JSP文件 

1. login.jsp

 

  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. <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN”>
  7. <html>
  8.   <head>
  9.     <base href=”<%=basePath%>”>
  10.     <title>My JSP ’index.jsp’ starting page</title>
  11.     <meta http-equiv=”pragma” content=”no-cache”>
  12.     <meta http-equiv=”cache-control” content=”no-cache”>
  13.     <meta http-equiv=”expires” content=”0″>
  14.     <meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
  15.     <meta http-equiv=”description” content=”This is my page”>
  16.     <!–
  17.     <link rel=”stylesheet” type=”text/css” href=”styles.css”>
  18.     –>
  19.   </head>
  20.   <body>
  21.   <form action=”${pageContext.request.contextPath}/user/login.action” method=”post”>
  22.      username:<input type=”text” name=”username”/> <br/>
  23.      password:<input type=”password” name=”password”/> <br/>
  24.     <input type=”submit” value=”login”/><input type=”reset” value=”reset”/>
  25.   </form>
  26.   </body>
  27. </html>

2. success.jsp 

 

  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. <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN”>
  7. <html>
  8.   <head>
  9.     <base href=”<%=basePath%>”>
  10.     <title>My JSP ’index.jsp’ starting page</title>
  11.     <meta http-equiv=”pragma” content=”no-cache”>
  12.     <meta http-equiv=”cache-control” content=”no-cache”>
  13.     <meta http-equiv=”expires” content=”0″>
  14.     <meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
  15.     <meta http-equiv=”description” content=”This is my page”>
  16.     <!–
  17.     <link rel=”stylesheet” type=”text/css” href=”styles.css”>
  18.     –>
  19.   </head>
  20.   <body>
  21.    欢迎您:{username}!
  22.   </body>
  23. </html>

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

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

2014-03-29

       布丰(bufoon)

更正(struts.xml文件)感谢u013506859提出

请注明转载出处

http://blog.csdn.net/songanling/article/details/22454973

http://blog.csdn.net/lqclh502/article/details/23435463