s2sh整合的登陆

此次整合的版本是:struts2.1.8 + spring2.5.6 + hibernate3.3.2

一.先整合hibernate和spring:

hibernate所需要jar包:antlr-2.7.6.jar、commons-collections-3.1.jar、dom4j-1.6.1.jar、hibernate3.jar、javassist-3.9.0.GA.jar、jta-1.1.jar、slf4j-api-1.5.8.jar、log4j.jar、slf4j-log4j12-1.5.8.jar (slf4j接口以log4j形式实现),因为采用了注解的方式所以还需(annotation3.4的包):ejb3-persistence.jar、hibernate-annotations.jar、hibernate-commons-annotations.jar、hibernate-entitymanager.jar ,采用了c3p0连接池,还需要:c3p0-0.9.1.2.jar

spring所需要jar包:spring.jar、commons-logging.jar ,spring注解需要:common-annotations.jar ,aop需要:aspectjrt.jar、aspectjweaver.jar、cglib-nodep-2.1_3.jar

 

hibernate.cfg.xml配置:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/oa
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="myeclipse.connection.profile">mysql5</property>
		<property name="show_sql">true</property>
		<property name="current_session_context_class">thread</property>
		<property name="hbm2ddl.auto">update</property>

		<!-- 首先说明我是使用c3p0连接池的方式 -->
		<property name="connection.provider_class">
			org.hibernate.connection.C3P0ConnectionProvider
		</property>
		<!-- 最大连接数 -->
		<property name="hibernate.c3p0.max_size">20</property>
		<!-- 最小连接数 -->
		<property name="hibernate.c3p0.min_size">2</property>
		<!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
		<property name="hibernate.c3p0.timeout">5000</property>
		<!-- 最大的PreparedStatement的数量 -->
		<property name="hibernate.c3p0.max_statements">100</property>
		<!-- 每隔1000秒检查连接池里的空闲连接 ,单位是秒-->
		<property name="hibernate.c3p0.idle_test_period">1000</property>
		<!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<!-- 每次都验证连接是否可用 -->
		<property name="hibernate.c3p0.validate">true</property>
		
		<mapping class="com.fsj.model.User" />

	</session-factory>

</hibernate-configuration>

 applicationContext.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx
		   http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
		   
	<context:component-scan base-package="com.fsj" /><!-- 启用自动扫描 -->
	<!-- 基于hibernate注解的sessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml">
		</property>
	</bean>
	<!-- 基于hibernate的事务管理器 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 采用注解形式的声明式事务管理 -->
	<tx:annotation-driven transaction-manager="txManager"/>
	
</beans>

 

User类采用hibernate的注解形式:

package com.fsj.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "_user")
public class User implements java.io.Serializable {

	private static final long serialVersionUID = -3564872478826196506L;	
	private Integer uid;
	private String uname;
	private String upwd;

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "u_id", unique = true, nullable = false)
	public Integer getUid() {
		return this.uid;
	}

	public void setUid(Integer UId) {
		this.uid = UId;
	}

	@Column(name = "u_name", length = 20)
	public String getUname() {
		return this.uname;
	}

	public void setUname(String UName) {
		this.uname = UName;
	}

	@Column(name = "u_pwd", length = 20)
	public String getUpwd() {
		return this.upwd;
	}

	public void setUpwd(String UPwd) {
		this.upwd = UPwd;
	}

}

DAO层的实现类为:

package com.fsj.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.fsj.dao.UserDao;
import com.fsj.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

	private HibernateTemplate hibernateTemplate;
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
        @SuppressWarnings("unchecked")
	public User login(String name, String pwd) {		
		List<User> users= hibernateTemplate.find("from User where uname=? and upwd=?",new Object[]{name,pwd});		
		System.out.println(users.size()+"-------------");
		return (users==null || users.size()==0)?null:(User)users.get(0);
	}

}

 service层的实现类采用事务管理:

package com.fsj.sevice.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fsj.dao.UserDao;
import com.fsj.model.User;
import com.fsj.sevice.UserService;

@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public User login(String name, String pwd) {
        return userDao.login(name, pwd);
    }

}

 

junit测试成功后,再加入struts2:

加入包:xwork-core-2.1.6.jar、struts2-core-2.1.8.jar、ognl-2.7.3.jar、freemarker-2.3.15.jar、commons-io-1.3.2.jar、commons-fileupload-1.2.1.jar、struts2-spring-plugin-2.1.8.jar

web.xml如下设置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<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>OpenSessionInViewFilter</filter-name>
	        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
	</filter>
	<filter-mapping>
	        <filter-name>OpenSessionInViewFilter</filter-name>
	        <url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>	
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
		
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
		
</web-app>

 

struts.xml如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

	<!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 -->
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
	<constant name="struts.serve.static.browserCache" value="false" />
	<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
	<constant name="struts.configuration.xml.reload" value="true" />
	<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
	<constant name="struts.devMode" value="true" />
	<!-- 默认的视图主题 -->
	<constant name="struts.ui.theme" value="simple" />
	<!-- 把action对象交给spring创建 -->
	<constant name="struts.objectFactory" value="spring" />

	<package name="myDefault" extends="struts-default">
		<default-action-ref name="indexPage" />
		<global-results>
			<result name="exceptionPage">/WEB-INF/exceptionPage.jsp
			</result>
		</global-results>
		<global-exception-mappings>
			<exception-mapping result="exceptionPage" exception="java.lang.Exception" />
		</global-exception-mappings>		
		<action name="indexPage">
			<result>/login.jsp</result>
		</action>
	</package>

	<package name="user" namespace="/user" extends="myDefault">
		<!-- 这里面的class不是指完整类路径,而是指在spring中定义的bean的名称 -->
		<action name="*UserAction" class="userAction" method="{1}">
			<result name="success">/WEB-INF/user/loginSuccess.jsp</result>
			<result name="input">/login.jsp</result>
		</action>
	</package>

</struts>

 UserAction类:

package com.fsj.web;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fsj.model.User;
import com.fsj.sevice.UserService;
import com.opensymphony.xwork2.ActionSupport;
@Controller("userAction")@Scope("prototype")
public class UserAction extends ActionSupport implements SessionAware{

	private Map<String, Object> session;
	private User user;
	@Resource
	private UserService userService;
	
	public String getResult() {
		return result;
	}

	public String login()
	{
		User logindUser = userService.login(user.getUname(), user.getUpwd());
		if(logindUser==null)
		{
			addActionError("用户名或密码错误,请重新输入。");
			return INPUT;
		}
		session.put("user", logindUser);
		return SUCCESS;
	}
		
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}

与UserAction同一包中建立验证文件:UserAction-validation.xml

 

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE validators PUBLIC 
  		"-//OpenSymphony Group//XWork Validator 1.0.2//EN" 
  		"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
	<field name="user.uname">
		<field-validator type="requiredstring">
			<message>登录的用户名不能为空</message>
		</field-validator>
		<field-validator type="regex">
			<param name="expression">^[a-zA-Z][a-zA-Z0-9_]{3,14}$</param>
			<message>登录的用户名必须以字母开始,后面跟字母、数字或_,长度为4-15位</message>
		</field-validator>
	</field>
	
	<field name="user.upwd">
		<field-validator type="requiredstring">
			<message>登录的密码不能为空</message>
		</field-validator>
		<field-validator type="regex">
			<param name="expression">^[a-zA-Z0-9!@#]{4,15}$</param>
			<message>登录的密码可以由字母、数字和! @ # 组成,长度为4-15位</message>
		</field-validator>
	</field>
</validators>

 

 login.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>登陆</title>
  </head>
  
  <body>
  	<s:head/>
  	<s:actionerror/>
        <s:fielderror />
    <s:form action="loginUserAction" namespace="/user" method="post">
    	<s:textfield label="用户名" name="user.uname" />
    	<s:password label="密码" name="user.upwd" />
    	<s:submit value="登陆" />
    </s:form>
  </body>
</html>

你可能感兴趣的:(spring,AOP,xml,Hibernate,struts)