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

  Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合_第1张图片

Hibernate

4.3.4   Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合_第2张图片

spring

4.0.2Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合_第3张图片


其它


二. 创建一张表

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的目录结构

Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合_第4张图片

Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合_第5张图片

四. 配置文件

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> 
   
  <!-- 添加对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>
     
  <!-- 添加对struts2的支持 -->
  <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" />
 
	<!-- 数据库连接池c3p0配置 -->
	<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>
	
	<!-- session工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
		<!-- 自动扫描注解方式配置的hibernate类文件 -->
		<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>
 
	<!-- 自动加载构建bean -->
	<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'?-->
 
 
<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>
 
        <!-- 显示sql语句 -->
        <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 struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
	<!-- 配置为开发模式 -->
    <constant name="struts.devMode" value="false" />
	<!-- 配置扩展名为action -->
    <constant name="struts.action.extension" value="action" />
    <!-- 配置主题 -->
    <constant name="struts.ui.theme" value="simple" />
    <!-- 配置上传文件大小此处默认为20M -->
    <constant name="struts.multipart.maxSize" value="2097152" />
    
    <!-- 国际化编码 -->   
    <constant name="struts.i18n.encoding" value="UTF-8" />   
    <!-- 定位视图资源的根路径。默认值为/WEB-INF/content -->   
    <constant value="/WEB-INF/templates" name="struts.convention.result.path" />   
    <!-- 指定convention扫描以xxx结尾的包 -->   
    <constant value="action" name="struts.convention.package.locators" />   
    <!-- 是否将Action类转换成小写 -->   
    <constant value="false" name="struts.convention.package.lowercase" />      
       
	<!-- 是否将actionName分割,去掉action部分,以大写字母作为分割 -->
	<constant name="struts.convention.action.name.separator" value="_" />
	<!-- 浏览器是否缓存静态内容 ,开发阶段最好关闭-->
    <constant name="struts.serve.static.browserCache" value="false"/>
	<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 --> 
    <constant name="struts.configuration.xml.reload" value="true"/>    
    <!-- 配置使用Spring管理Action -->
    <constant name="struts.objectFactory" value="spring"/>
    <!-- 让struts2始终先考虑spring的自动装箱   -->
    <constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true" />
	<!-- 设置默认的父包
	<constant value="MAIN" name="struts.convention.default.parent.package" />
	<package name="MAIN" extends="struts-default" namespace="/">
	</package>
	 -->

	
    <package name="default" namespace="/" extends="struts-default">
		<interceptors>
			<!--  声明一个拦截器   进行登录检查  -->
			<interceptor name="checkePrivilege" class="com.oa168.interceptor.CheckPrivilegeInterceptor"></interceptor>
			
			<!--  重新定义defaultStack拦截器栈,需要先判断权限    --> 
			<interceptor-stack name="defaultStack">
				<interceptor-ref name="checkePrivilege" />
				<interceptor-ref name="defaultStack" />
			</interceptor-stack>
		</interceptors>
		 
		<!-- 配置全局的Result -->
		<global-results>
			<result name="loginUI">/WEB-INF/jsp/userAction/loginUI.jsp</result>
			<result name="noPrivilegeError">/noPrivilegeError.jsp</result>
		</global-results>
		
		<!-- 测试用的action,当与Spring整合后,class属性写的就是Spring中bean的名称 
		     不需要写com.oa168.test.TestAction形式
		     所以整合就是在Action类中加入@Controller  @Scope("prototype")
		     并在Web.xml中加入监听器
		<listener>
			<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener>
		<context-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext*.xml</param-value>
		</context-param>
		   -->
		<action name="test" class="testAction">
			<result name="success">/test.jsp</result>
		</action> 
    
		<!-- 首页 -->
		<action name="homeAction_*" class="homeAction" method="{1}">
			<result name="{1}">/WEB-INF/jsp/homeAction/{1}.jsp</result>
			<!-- 
			<result name="index">/WEB-INF/jsp/homeAction/Index.jsp</result>
			<result name="top">/WEB-INF/jsp/homeAction/Top.jsp</result>
			<result name="bottom">/WEB-INF/jsp/homeAction/Bottom.jsp</result>
			<result name="left">/WEB-INF/jsp/homeAction/Left.jsp</result>
			<result name="mainFrame">/WEB-INF/jsp/homeAction/MainFrame.jsp</result> -->
		</action>
		 
    </package>

</struts>


 

FreeMark的配置

 

为了在FreeMarker模板中使用标签库,可按如下步骤进行

1.将struts-tags.tld文件复制到WEB-INF目录下

   即将系统所需的标签库定义文件(*.tld文件)复制到web应用中。对于基于struts2框架的JAVA_Web应用,则需要将Struts2-core.jar包解压,取出其中的struts-tags.tld文件,并复制到web应用的WEB-INF目录下。同时所需的最少Jar包如下图

Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合_第6张图片

2.在web.xml文件中启动JspSupportServlet

  在web.xml文件中作如下配置,如下:

  <servlet>
 <servlet-name>JspSupportServlet</servlet-name>
 <servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
       <!--配置JspSupportServlet自启动-->
 <load-on-startup>1</load-on-startup>
 </servlet>

此配置本人没配FreeMark一样可以,具体用处有待研究。

 

3. 在FreeMarker模板文件中使用“assign指令”导入标签库

 导入标签库的代码如下:

<#--定义web-inf/strust-tags.tld文件对应的标签库前缀为s-->
 <#assigns=JspTaglibs["/WEB-INF/struts-tags.tld"]/>

说明:在上面导入的标签库定义文件中,指定了标签库前缀为s,而该前缀对应的标签库定义文件主放置在/WEB-INF/struts-tags.tld路径下、

4.完毕

经过上述步骤后,即可在应用的FreeMarker模板中使用Struts2标签。在FreeMarker模板中增加了标签库定义后,就可以在FreeMarker模板中使用Struts2标签了。在FreeMarker使用标签与在jsp中使用标签略有差别.

补充说明

   我们不能直接通过浏览器直接请求该页面,否则看到的不是我们想要的结果,而是该模板页面的源代码(因为WEB容器默认不会处理 FreeMarker模板页面)。

        正如前面使用FreeMarker模板作为视图组件时看到的,FreeMarker作为视图组件是由Servlet负责加载该模板,并使用数据模型填充该模板,并且填充后的标准HTML响应输出给浏览者。

   在Strtus2框架的支持下,Struts2框架充当了之前的Servlet角色只要浏览者的请求经过了Struts2处理后,Struts2框架就会自动加载FreeMarker模板,并使用数据模型填充该模板,并且将最后的HTML页面输出给浏览者.。

   为了让所有的用户请求都经过Struts2框架处理,我们将所有的FreeMarker模板文件放在web-inf/ftl路径下.

   因为浏览者无法直接访问web-inf/ftl路径下的资源,所以我们在struts.xml配置文中增加了如下配置片段:

 <action name="*">
           <result type="freemarker">/WEB-INF/ftl/{1}.ftl</result>
       </action>

也就是把原来的Action中的result属性中type值改成“freemarker”

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;
 
/**
 * 基础数据库操作类
 * 
 * @author ss
 * 
 */
public interface BaseDAO<T> {
 
	/**
	 * 保存一个对象
	 * 
	 * @param o
	 * @return
	 */
	public Serializable save(T o);
 
	/**
	 * 删除一个对象
	 * 
	 * @param o
	 */
	public void delete(T o);
 
	/**
	 * 更新一个对象
	 * 
	 * @param o
	 */
	public void update(T o);
 
	/**
	 * 保存或更新对象
	 * 
	 * @param o
	 */
	public void saveOrUpdate(T o);
 
	/**
	 * 查询
	 * 
	 * @param hql
	 * @return
	 */
	public List<T> find(String hql);
 
	/**
	 * 查询集合
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public List<T> find(String hql, Object[] param);
 
	/**
	 * 查询集合
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public List<T> find(String hql, List<Object> param);
 
	/**
	 * 查询集合(带分页)
	 * 
	 * @param hql
	 * @param param
	 * @param page
	 *            查询第几页
	 * @param rows
	 *            每页显示几条记录
	 * @return
	 */
	public List<T> find(String hql, Object[] param, Integer page, Integer rows);
 
	/**
	 * 查询集合(带分页)
	 * 
	 * @param hql
	 * @param param
	 * @param page
	 * @param rows
	 * @return
	 */
	public List<T> find(String hql, List<Object> param, Integer page, Integer rows);
 
	/**
	 * 获得一个对象
	 * 
	 * @param c
	 *            对象类型
	 * @param id
	 * @return Object
	 */
	public T get(Class<T> c, Serializable id);
 
	/**
	 * 获得一个对象
	 * 
	 * @param hql
	 * @param param
	 * @return Object
	 */
	public T get(String hql, Object[] param);
 
	/**
	 * 获得一个对象
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public T get(String hql, List<Object> param);
 
	/**
	 * select count(*) from 类
	 * 
	 * @param hql
	 * @return
	 */
	public Long count(String hql);
 
	/**
	 * select count(*) from 类
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public Long count(String hql, Object[] param);
 
	/**
	 * select count(*) from 类
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public Long count(String hql, List<Object> param);
 
	/**
	 * 执行HQL语句
	 * 
	 * @param hql
	 * @return 响应数目
	 */
	public Integer executeHql(String hql);
 
	/**
	 * 执行HQL语句
	 * 
	 * @param hql
	 * @param param
	 * @return 响应数目
	 */
	public Integer executeHql(String hql, Object[] param);
 
	/**
	 * 执行HQL语句
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public Integer executeHql(String hql, List<Object> param);
 
}


2. BaseDAOImpl.java

package com.bufoon.dao.impl;
 
import java.io.Serializable;
import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import com.bufoon.dao.BaseDAO;
 
@Repository("baseDAO")
@SuppressWarnings("all")
public class BaseDAOImpl<T> implements BaseDAO<T> {
 
	private SessionFactory sessionFactory;
 
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
 
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
 
	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
 
	public Serializable save(T o) {
		return this.getCurrentSession().save(o);
	}
 
	public void delete(T o) {
		this.getCurrentSession().delete(o);
	}
 
	public void update(T o) {
		this.getCurrentSession().update(o);
	}
 
	public void saveOrUpdate(T o) {
		this.getCurrentSession().saveOrUpdate(o);
	}
 
	public List<T> find(String hql) {
		return this.getCurrentSession().createQuery(hql).list();
	}
 
	public List<T> find(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}
 
	public List<T> find(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.list();
	}
 
	public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}
 
	public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}
 
	public T get(Class<T> c, Serializable id) {
		return (T) this.getCurrentSession().get(c, id);
	}
 
	public T get(String hql, Object[] param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}
 
	public T get(String hql, List<Object> param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}
 
	public Long count(String hql) {
		return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
	}
 
	public Long count(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return (Long) q.uniqueResult();
	}
 
	public Long count(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return (Long) q.uniqueResult();
	}
 
	public Integer executeHql(String hql) {
		return this.getCurrentSession().createQuery(hql).executeUpdate();
	}
 
	public Integer executeHql(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.executeUpdate();
	}
 
	public Integer executeHql(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.executeUpdate();
	}
 
}


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 {
 
    /**
     * 对字符串进行MD5加密
     * 
     * @param str
     * @return String
     */
    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;
    }
     
 
    /**
     * 判断字符串是否为空
     * 
     * @param str
     *            字符串
     * @return true:为空; false:非空
     */
    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+"/";
%>
 
 
<html>
   
    <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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
   
   
   
  <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>

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+"/";
%>
 
 
 
   
    <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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
   
   
   
  <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>

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

你可能感兴趣的:(Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合)