S2SH 框架 基于annotation配置

S2SH 框架 基于annotation配置

此次整合的版本是: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、hibernate- validator.jar、jboss-archive-browsing.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代码
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8.     <session-factory>  
  9.         <property name="dialect">  
  10.             org.hibernate.dialect.MySQLDialect  
  11.         </property>  
  12.         <property name="connection.url">  
  13.             jdbc:mysql://localhost:3306/oa  
  14.         </property>  
  15.         <property name="connection.username">root</property>  
  16.         <property name="connection.password">root</property>  
  17.         <property name="connection.driver_class">  
  18.             com.mysql.jdbc.Driver  
  19.         </property>  
  20.         <property name="myeclipse.connection.profile">mysql5</property>  
  21.         <property name="show_sql">true</property>  
  22.         <property name="current_session_context_class">thread</property>  
  23.         <property name="hbm2ddl.auto">update</property>  
  24.   
  25.         <!-- 首先说明我是使用c3p0连接池的方式 -->  
  26.         <property name="connection.provider_class">  
  27.             org.hibernate.connection.C3P0ConnectionProvider  
  28.         </property>  
  29.         <!-- 最大连接数 -->  
  30.         <property name="hibernate.c3p0.max_size">20</property>  
  31.         <!-- 最小连接数 -->  
  32.         <property name="hibernate.c3p0.min_size">2</property>  
  33.         <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->  
  34.         <property name="hibernate.c3p0.timeout">5000</property>  
  35.         <!-- 最大的PreparedStatement的数量 -->  
  36.         <property name="hibernate.c3p0.max_statements">100</property>  
  37.         <!-- 每隔1000秒检查连接池里的空闲连接 ,单位是秒-->  
  38.         <property name="hibernate.c3p0.idle_test_period">1000</property>  
  39.         <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->  
  40.         <property name="hibernate.c3p0.acquire_increment">2</property>  
  41.         <!-- 每次都验证连接是否可用 -->  
  42.         <property name="hibernate.c3p0.validate">true</property>  
  43.           
  44.         <mapping class="com.fsj.model.User" />  
  45.   
  46.     </session-factory>  
  47.   
  48. </hibernate-configuration>  
<?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代码
  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" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.            http://www.springframework.org/schema/context  
  8.            http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  9.            http://www.springframework.org/schema/aop  
  10.            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  11.            http://www.springframework.org/schema/tx  
  12.            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  13.              
  14.     <context:component-scan base-package="com.fsj" /><!-- 启用自动扫描 -->  
  15.     <!-- 基于hibernate注解的sessionFactory -->  
  16.     <bean id="sessionFactory"  
  17.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  18.         <property name="configLocation" value="classpath:hibernate.cfg.xml">  
  19.         </property>  
  20.     </bean>  
  21.     <!-- 基于hibernate的事务管理器 -->  
  22.     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  23.         <property name="sessionFactory" ref="sessionFactory" />  
  24.     </bean>  
  25.     <!-- 采用注解形式的声明式事务管理 -->  
  26.     <tx:annotation-driven transaction-manager="txManager"/>  
  27.       
  28. </beans>  
<?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的注解形式:

Java代码
  1. package com.fsj.model;  
  2.   
  3. import javax.persistence.Column;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import static javax.persistence.GenerationType.IDENTITY;  
  7. import javax.persistence.Id;  
  8. import javax.persistence.Table;  
  9.   
  10. @Entity  
  11. @Table(name = "_user")  
  12. public class User implements java.io.Serializable {  
  13.   
  14.     private static final long serialVersionUID = -3564872478826196506L;   
  15.     private Integer uid;  
  16.     private String uname;  
  17.     private String upwd;  
  18.   
  19.     @Id  
  20.     @GeneratedValue(strategy = IDENTITY)  
  21.     @Column(name = "u_id", unique = true, nullable = false)  
  22.     public Integer getUid() {  
  23.         return this.uid;  
  24.     }  
  25.   
  26.     public void setUid(Integer UId) {  
  27.         this.uid = UId;  
  28.     }  
  29.   
  30.     @Column(name = "u_name", length = 20)  
  31.     public String getUname() {  
  32.         return this.uname;  
  33.     }  
  34.   
  35.     public void setUname(String UName) {  
  36.         this.uname = UName;  
  37.     }  
  38.   
  39.     @Column(name = "u_pwd", length = 20)  
  40.     public String getUpwd() {  
  41.         return this.upwd;  
  42.     }  
  43.   
  44.     public void setUpwd(String UPwd) {  
  45.         this.upwd = UPwd;  
  46.     }  
  47.   
  48. }  
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层的实现类为:

Java代码
  1. package com.fsj.dao.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.hibernate.SessionFactory;  
  8. import org.springframework.orm.hibernate3.HibernateTemplate;  
  9. import org.springframework.stereotype.Repository;  
  10.   
  11. import com.fsj.dao.UserDao;  
  12. import com.fsj.model.User;  
  13.   
  14. @Repository("userDao")  
  15. public class UserDaoImpl implements UserDao {  
  16.   
  17.     private HibernateTemplate hibernateTemplate;  
  18.       
  19.     @Resource  
  20.     public void setSessionFactory(SessionFactory sessionFactory)  
  21.     {  
  22.         this.hibernateTemplate = new HibernateTemplate(sessionFactory);  
  23.     }  
  24.         @SuppressWarnings("unchecked")  
  25.     public User login(String name, String pwd) {          
  26.         List<User> users= hibernateTemplate.find("from User where uname=? and upwd=?",new Object[]{name,pwd});          
  27.         System.out.println(users.size()+"-------------");  
  28.         return (users==null || users.size()==0)?null:(User)users.get(0);  
  29.     }  
  30.   
  31. }  
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层的实现类采用事务管理:

Java代码
  1. package com.fsj.sevice.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.stereotype.Service;  
  8. import org.springframework.transaction.annotation.Propagation;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10.   
  11. import com.fsj.dao.UserDao;  
  12. import com.fsj.model.User;  
  13. import com.fsj.sevice.UserService;  
  14.   
  15. @Service("userService")  
  16. @Transactional(rollbackFor = Exception.class)  
  17. public class UserServiceImpl implements UserService {  
  18.   
  19.     @Resource  
  20.     private UserDao userDao;  
  21.     @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)  
  22.     public User login(String name, String pwd) {  
  23.         return userDao.login(name, pwd);  
  24.     }  
  25.   
  26. }  
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代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  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_2_5.xsd">  
  7.       
  8.     <context-param>  
  9.        <param-name>contextConfigLocation</param-name>  
  10.        <param-value>classpath:applicationContext.xml</param-value>  
  11.     </context-param>  
  12.       
  13.     <listener>  
  14.           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  15.     </listener>  
  16.           
  17.     <filter>  
  18.         <filter-name>struts2</filter-name>  
  19.         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  20.     </filter>   
  21.     <filter-mapping>  
  22.         <filter-name>struts2</filter-name>  
  23.         <url-pattern>/*</url-pattern>  
  24.     </filter-mapping>  
  25.           
  26.     <filter>  
  27.         <filter-name>encoding</filter-name>  
  28.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  29.         <init-param>  
  30.             <param-name>encoding</param-name>  
  31.             <param-value>UTF-8</param-value>  
  32.         </init-param>  
  33.     </filter>  
  34.     <filter-mapping>  
  35.         <filter-name>encoding</filter-name>  
  36.         <url-pattern>/*</url-pattern>  
  37.     </filter-mapping>  
  38.           
  39.                           
  40.     <filter>  
  41.             <filter-name>OpenSessionInViewFilter</filter-name>  
  42.             <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>  
  43.     </filter>  
  44.     <filter-mapping>  
  45.             <filter-name>OpenSessionInViewFilter</filter-name>  
  46.             <url-pattern>/*</url-pattern>  
  47.     </filter-mapping>  
  48.       
  49. </web-app>  
<?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>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>
<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>
</web-app>
 

struts.xml如下:

Xml代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.   
  6. <struts>  
  7.   
  8.     <!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的 setCharacterEncoding方法 -->  
  9.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  10.     <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关 闭 -->  
  11.     <constant name="struts.serve.static.browserCache" value="false" />  
  12.     <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使 用),开发阶段最好打开 -->  
  13.     <constant name="struts.configuration.xml.reload" value="true" />  
  14.     <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->  
  15.     <constant name="struts.devMode" value="true" />  
  16.     <!-- 默认的视图主题 -->  
  17.     <constant name="struts.ui.theme" value="simple" />  
  18.     <!-- 把action对象交给spring创建 -->  
  19.     <constant name="struts.objectFactory" value="spring" />  
  20.   
  21.     <package name="myDefault" extends="struts-default">  
  22.         <default-action-ref name="indexPage" />  
  23.         <global-results>  
  24.             <result name="exceptionPage">/WEB-INF/exceptionPage.jsp  
  25.             </result>  
  26.         </global-results>  
  27.         <global-exception-mappings>  
  28.             <exception-mapping result="exceptionPage" exception="java.lang.Exception" />  
  29.         </global-exception-mappings>        
  30.         <action name="indexPage">  
  31.             <result>/login.jsp</result>  
  32.         </action>  
  33.     </package>  
  34.   
  35.     <package name="user" namespace="/user" extends="myDefault">  
  36.         <!-- 这里面的class不是指完整类路径,而是指在spring中定义的bean的名称 -->  
  37.         <action name="*UserAction" class="userAction" method="{1}">  
  38.             <result name="success">/WEB-INF/user/loginSuccess.jsp</result>  
  39.             <result name="input">/login.jsp</result>  
  40.         </action>  
  41.     </package>  
  42.   
  43. </struts>  
<?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类:

Java代码
  1. package com.fsj.web;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.apache.struts2.interceptor.SessionAware;  
  8. import org.springframework.context.annotation.Scope;  
  9. import org.springframework.stereotype.Controller;  
  10.   
  11. import com.fsj.model.User;  
  12. import com.fsj.sevice.UserService;  
  13. import com.opensymphony.xwork2.ActionSupport;  
  14. @Controller("userAction")@Scope("prototype")  
  15. public class UserAction extends ActionSupport implements SessionAware{  
  16.   
  17.     private Map<String, Object> session;  
  18.     private User user;  
  19.     @Resource  
  20.     private UserService userService;  
  21.       
  22.     public String getResult() {  
  23.         return result;  
  24.     }  
  25.   
  26.     public String login()  
  27.     {  
  28.         User logindUser = userService.login(user.getUname(), user.getUpwd());  
  29.         if(logindUser==null)  
  30.         {  
  31.             addActionError("用户名或密码错误,请重新输入。");  
  32.             return INPUT;  
  33.         }  
  34.         session.put("user", logindUser);  
  35.         return SUCCESS;  
  36.     }  
  37.           
  38.     public User getUser() {  
  39.         return user;  
  40.     }  
  41.   
  42.     public void setUser(User user) {  
  43.         this.user = user;  
  44.     }  
  45.   
  46.     public void setSession(Map<String, Object> session) {  
  47.         this.session = session;  
  48.     }  
  49. }  
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代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.  <!DOCTYPE validators PUBLIC   
  3.         "-//OpenSymphony Group//XWork Validator 1.0.2//EN"   
  4.         "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">  
  5.   
  6. <validators>  
  7.     <field name="user.uname">  
  8.         <field-validator type="requiredstring">  
  9.             <message>登录的用户名不能为空</message>  
  10.         </field-validator>  
  11.         <field-validator type="regex">  
  12.             <param name="expression">^[a-zA-Z][a-zA-Z0-9_]{3,14}$</param>  
  13.             <message>登录的用户名必须以字母开始,后面跟字母、数字或_,长度为4-15位</message>  
  14.         </field-validator>  
  15.     </field>  
  16.       
  17.     <field name="user.upwd">  
  18.         <field-validator type="requiredstring">  
  19.             <message>登录的密码不能为空</message>  
  20.         </field-validator>  
  21.         <field-validator type="regex">  
  22.             <param name="expression">^[a-zA-Z0-9!@#]{4,15}$</param>  
  23.             <message>登录的密码可以由字母、数字和! @ # 组成,长度为4-15位</message>  
  24.         </field-validator>  
  25.     </field>  
  26. </validators>  
<?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页面:

Jsp代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">     
  12.     <title> 登陆</title>  
  13.   </head>  
  14.     
  15.   <body>  
  16.     <s:head/>  
  17.     <s:actionerror/>  
  18.         <s:fielderror />  
  19.     <s:form action="loginUserAction" namespace="/user" method="post">  
  20.         <s:textfield label="用户名" name="user.uname" />  
  21.         <s:password label="密码" name="user.upwd" />  
  22.         <s:submit value="登陆" />  
  23.     </s:form>  
  24.   </body>  
  25. </html>  
<%@ 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>

你可能感兴趣的:(S2SH 框架 基于annotation配置)