ssh搭建开发环境

  1. 云栖社区>
  2. 博客>
  3. 正文

ssh搭建开发环境

code_xzh 2014-03-26 09:11:00 浏览1110
展开阅读全文

公司一直不是ssh零配置的框架,每次写action都要在applicationcontext和struts里面配置,好麻烦,最近有空,写了一个ssh零配置的框架

这里写了一个小的项目,以用户权限管理为例

先做准备工作:

1.struts2去官网下载最新版struts开发包http://struts.apache.org/download.cgi#struts216

2.hibernate4去官网下载最新版hibernate4开发包http://sourceforge.net/projects/hibernate/files/hibernate4/

3.spring3去官网下载最新版spring3开发包http://www.springsource.org/download/community

一、先建立一个空的web的项目sshFrame,加载必须的包

1.添加struts2必备的包。我下载的是最近的struts2.3.8

asm-3.3.jar  --ASM字节码库 ,使用“cglib”则必要

aopalliance-1.0.jar  --这个包为AOP提供了最普通和通用的接口

commons-fileupload-1.2.2.jar   --Struts2上传下载的jar

commons-io-2.0.1.jar  --Struts2上传下载的jar

commons-logging-1.1.1.jar   --Jakarta的通用日志记录包

freemarker-2.3.19.jar

ognl-3.0.6.jar    --支持ognl表达式

struts2-core-2.3.8.jar  --struts2的核心包

struts2-spring-plugin-2.3.8.jar     --struts2与spring整合所需

struts2-convention-plugin-2.3.8.jar  --struts2零配置注释用

xwork-core-2.3.8.jar 

可以不加 struts2-config-browser-plugin-2.3.8.jar为struts协助开发需要的包:可以输入http://127.0.0.1:8686/config-browser/actionNames.action查看系统所有已经存在的action,配置不正确就可以在这里看出来;

2.添加Hibernate 所需要的包。hibernate-4.1.9.Final

把下载下来的hibernate\lib\required下的包全部拷贝进去,分别是

antlr-2.7.7.jar  --语言转换工具,hibernate用他将hql语句转换为sql语句

dom4j-1.6.1.jar  --解析xml文档的工具

hibernate-commons-annotations-4.0.1.Final.jar

hibernate-core-4.1.9.Final.jar  --核心包

hibernate-jpa-2.0-api-1.0.1.Final.jar

javassist-3.17.1-GA.jar

jboss-logging-3.1.0.GA.jar

jboss-transaction-api_1.1_spec-1.0.0.Final.jar

还有加入hibernate\lib\optional\c3p0\c3p0-0.9.1.jar

hibernate-ehcache-4.1.9.Final.jar

ehcache-core-2.4.3.jar

slf4j-api-1.6.4.jar

slf4j-log4j12-1.6.4.jar

3添加spring3 所需要的包 spring-framework-3.2.0.RELEASE

spring-aop-3.2.0.RELEASE.jar

spring-aspects-3.2.0.RELEASE.jar

spring-beans-3.2.0.RELEASE.jar

spring-context-3.2.0.RELEASE.jar

spring-core-3.2.0.RELEASE.jar

spring-expression-3.2.0.RELEASE.jar

spring-instrument-3.2.0.RELEASE.jar

spring-jdbc-3.2.0.RELEASE.jar

spring-jms-3.2.0.RELEASE.jar

spring-orm-3.2.0.RELEASE.jar

spring-oxm-3.2.0.RELEASE.jar

spring-test-3.2.0.RELEASE.jar --测试时用

spring-tx-3.2.0.RELEASE.jar  --事务处理所用

spring-web-3.2.0.RELEASE.jar

aspectjweaver-1.5.3.jar  --spring所依赖的包

 

其他

asm-commons-3.3.jar

Commons—pool.jar ,commons-dbcp.jar  ----------DBCP数据库连接池,Apache的jakarta组织开发 的,tomcat连接池也是dbcp(可选)

cglib.jar----------------------------高效的代码生成工具, Hibernate用它在运行时扩展 Java类和实现 Java 接

jta.jar  --标准的JTA API(JTA即java事物API,JTA事务比JDBC事务更强大。一个JTA事务可以有多个参与者,而一个JDBC事务则被限定在一个单一的数据库连接),我暂时还没加,先备着

mysql-connector-java-5.1.18-bin.jar

log4j-1.2.16.jar

二、添加配置文件

在struts包下struts\src\apps\blank\src\main\resources提供了空白的struts.xml文件,把它复制到项目的src下

web.xml中

  1. <!-- spring 配置 -->  
  2.   <listener>  
  3.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  4.   </listener>  
  5.   <context-param>  
  6.     <description>Spring上下文</description>  
  7.     <param-name>contextConfigLocation</param-name>  
  8.     <param-value>classpath:applicationContext*.xml</param-value>  
  9.   </context-param>  
  10.   
  11. <!-- hibernate 懒加载的问题过滤 ,可以不配置 -->  
  12.   <filter>  
  13.     <description>hibernate Session 过滤器</description>  
  14.     <filter-name>openSessionInViewFilter</filter-name>  
  15.     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
  16.   </filter>  
  17.   <filter-mapping>  
  18.     <filter-name>openSessionInViewFilter</filter-name>  
  19.     <url-pattern>/*</url-pattern>  
  20.   </filter-mapping>  
  21.   <filter>   
  22.  <!-- struts配置 -->  
  23.     <filter-name>struts2</filter-name>  
  24.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  25.   </filter>  
  26.   <filter-mapping>  
  27.     <filter-name>struts2</filter-name>  
  28.     <url-pattern>/*</url-pattern>  
  29.   </filter-mapping>  
  30.   
  31.    

struts.xml配置

  1. <struts>  
  2.   
  3. <!-- 使用Spring -->  
  4.  <constant name="struts.objectFactory" value="spring" />  
  5.  <constant name="struts.devMode" value="true" />  
  6.  <constant name="struts.configuration.xml.reload" value="true" />  
  7.    
  8.  <package name="default" extends="struts-default" namespace="/">  
  9.   <interceptors>  
  10.    <!-- 使用权限拦截 -->  
  11.    <interceptor name="authority" class="com.sshFrame.zero.interceptor.AuthorityInterceptor"/>  
  12.    <!-- 异常拦截 -->  
  13.    <interceptor name="exceptionInterceptor" class="com.sshFrame.zero.interceptor.ExceptionInterceptor"/>  
  14.    <!-- 解决struts安全漏洞,拦截所有的带有#号的url -->  
  15.    <interceptor-stack name="baseStack">  
  16.     <interceptor-ref name="authority"/>  
  17.     <interceptor-ref name="exceptionInterceptor"/>  
  18.     <interceptor-ref name="params">     
  19.      <param name="excludeParams">.*\\u0023.*</param>     
  20.     </interceptor-ref>  
  21.     <interceptor-ref name="defaultStack"/>  
  22.    </interceptor-stack>  
  23.   </interceptors>  
  24.   <!-- 配置默认拦截器栈 -->  
  25.   <default-interceptor-ref name="baseStack"/>  
  26.   <global-results>  
  27.    <result name="login">/index.jsp</result>  
  28.    <result name="error">/error.jsp</result>  
  29.   </global-results>  
  30.  </package>  
  31.   
  32. </struts>  

 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:context="http://www.springframework.org/schema/context"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"   
  7.     xmlns:tx="http://www.springframework.org/schema/tx"  
  8.     xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"  
  9.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  10.     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  11.     http://www.springframework.org/schema/context   
  12.     http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  13.     http://www.springframework.org/schema/aop  
  14.     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  15.     http://www.springframework.org/schema/tx  
  16.     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">  
  17.   
  18.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  19.         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
  20.         <property name="url" value="jdbc:mysql://127.0.0.1:3306/osdesignaid"></property>  
  21.         <property name="username" value="root"></property>  
  22.         <property name="password" value="root"></property>  
  23.     </bean>  
  24.     <bean id="sessionFactory"  
  25.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  26.         <property name="dataSource" ref="dataSource" />  
  27.         <property name="hibernateProperties">  
  28.             <props>  
  29.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
  30.                 <prop key="hibernate.current_session_context_class">thread</prop>  
  31.                 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</prop>  
  32.                 <prop key="hibernate.show_sql">true</prop>  
  33.                 <prop key="hibernate.format_sql">true</prop>  
  34.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  35.             </props>  
  36.         </property>  
  37.         <property name="packagesToScan">  
  38.             <list>  
  39.                 <value>com.sshFrame.zero.pojo</value>  
  40.                 <value>com.sshFrame.test.pojo</value>  
  41.                 </list>  
  42.         </property>  
  43.     </bean>  
  44.     <aop:aspectj-autoproxy /><!-- 代理 -->  
  45.     <!-- 定义事务管理器 -->  
  46.     <bean id="txManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  47.         <property name="sessionFactory" ref="sessionFactory" />  
  48.     </bean>  
  49.     <!-- 申明annotation 加载事务驱动 -->  
  50.     <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>  
  51.     <tx:advice id="txAdvice" transaction-manager="txManager">  
  52.         <tx:attributes>  
  53.             <tx:method name="save*" propagation="REQUIRED" />  
  54.             <tx:method name="add*" propagation="REQUIRED" />  
  55.             <tx:method name="create*" propagation="REQUIRED" />  
  56.             <tx:method name="insert*" propagation="REQUIRED" />  
  57.             <tx:method name="update*" propagation="REQUIRED" />  
  58.             <tx:method name="merge*" propagation="REQUIRED" />  
  59.             <tx:method name="del*" propagation="REQUIRED" />  
  60.             <tx:method name="remove*" propagation="REQUIRED" />  
  61.             <tx:method name="put*" propagation="REQUIRED" />  
  62.             <tx:method name="use*" propagation="REQUIRED"/>  
  63.   
  64.             <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->  
  65.             <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
  66.             <tx:method name="count*" propagation="REQUIRED" read-only="true" />  
  67.   
  68.             <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
  69.             <tx:method name="list*" propagation="REQUIRED" read-only="true" />  
  70.   
  71.             <tx:method name="*" read-only="true" />  
  72.         </tx:attributes>  
  73.     </tx:advice>  
  74.     <aop:config expose-proxy="true">  
  75.         <!-- 只对业务逻辑层实施事务 -->  
  76.         <aop:pointcut id="txPointcut" expression="execution(* cn.javass..service..*.*(..))" />  
  77.         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>  
  78.     </aop:config>  
  79.     <!-- 自动扫描包 -->  
  80.     <context:annotation-config />  
  81.     <context:component-scan base-package="com.sshFrame.zero.*,com.sshFrame.test.*" annotation-config="true"/>  
  82. </beans>  

三、写框架基类

改写基本的框架类了

Basedao

  1. package com.sshFrame.zero.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.ParameterizedType;  
  6. import java.lang.reflect.Type;  
  7. import java.util.List;  
  8.   
  9. import javax.persistence.Id;  
  10.   
  11. import org.hibernate.Criteria;  
  12. import org.hibernate.HibernateException;  
  13. import org.hibernate.Query;  
  14. import org.hibernate.Session;  
  15. import org.hibernate.SessionFactory;  
  16. import org.hibernate.criterion.Example;  
  17. import org.springframework.beans.factory.annotation.Autowired;  
  18.   
  19. /**  
  20.  * 基于hibernate的BaseDao  
  21.  * Spring3对Hibernate4已经没有了HibernateDaoSupport和HibernateTemplate的支持,使用了原生态的API  
  22.  * @author 雪精灵  
  23.  *  
  24.  * @param <T>  
  25.  */  
  26. public class BaseDao<T extends Serializable> {  
  27.     @Autowired  
  28.     private SessionFactory sessionFactory;  
  29.     //当前泛型类  
  30.     @SuppressWarnings("rawtypes")  
  31.     private Class entityClass;  
  32.     //当前主键名称  
  33.     private String pkname;  
  34.     private final String HQL_LIST_ALL;  
  35.     private final String HQL_COUNT_ALL;  
  36.     @SuppressWarnings("rawtypes")  
  37.     public Class getEntityClass() {  
  38.         return entityClass;  
  39.     }  
  40.     @SuppressWarnings("rawtypes")  
  41.     public void setEntityClass(Class entityClass) {  
  42.         this.entityClass = entityClass;  
  43.     }  
  44.       
  45.     @SuppressWarnings("rawtypes")  
  46.     public BaseDao() {  
  47.         //获取当前泛型类  
  48.         Type type = this.getClass().getGenericSuperclass();  
  49.         if (type.toString().indexOf("BaseDao") != -1) {  
  50.             ParameterizedType type1 = (ParameterizedType) type;  
  51.             Type[] types = type1.getActualTypeArguments();  
  52.             setEntityClass((Class) types[0]);  
  53.         }else{  
  54.             type = ((Class)type).getGenericSuperclass();  
  55.             ParameterizedType type1 = (ParameterizedType) type;  
  56.             Type[] types = type1.getActualTypeArguments();  
  57.             setEntityClass((Class) types[0]);  
  58.         }  
  59.         getPkname();  
  60.         HQL_LIST_ALL="from "+this.entityClass.getSimpleName()+" order by "+pkname+" desc";  
  61.         HQL_COUNT_ALL="select count(*) from "+this.entityClass.getSimpleName();  
  62.     }  
  63.     /**  
  64.      * 获取主键名称  
  65.      * @return  
  66.      */  
  67.     public String getPkname() {  
  68.         Field[] fields = this.entityClass.getDeclaredFields();//反射类字段  
  69.         for (Field field : fields) {  
  70.             field.isAnnotationPresent(Id.class);  
  71.             this.pkname=field.getName();  
  72.             break;  
  73.         }  
  74.         return pkname;  
  75.     }  
  76.     /**  
  77.      * 保存实例  
  78.      *   
  79.      * @param t  
  80.      * @throws HibernateException  
  81.      */  
  82.     public void save(T t) throws HibernateException{  
  83.         Session session=null;  
  84.         try {  
  85.             session=sessionFactory.openSession();  
  86.             session.beginTransaction();  
  87.             session.save(t);  
  88.             session.getTransaction().commit();  
  89.         } catch (HibernateException e) {  
  90.             e.printStackTrace();  
  91.             throw new HibernateException(e);  
  92.         }finally{  
  93.             session.close();  
  94.         }  
  95.     }  
  96.     /**  
  97.      * 修改实例  
  98.      *   
  99.      * @param t  
  100.      * @throws HibernateException  
  101.      */  
  102.     public void update(T t) throws HibernateException{  
  103.         Session session=null;  
  104.         try {  
  105.             session=sessionFactory.openSession();  
  106.             session.beginTransaction();  
  107.             session.update(t);  
  108.             session.getTransaction().commit();  
  109.         } catch (HibernateException e) {  
  110.             e.printStackTrace();  
  111.             throw new HibernateException(e);  
  112.         }finally{  
  113.             session.close();  
  114.         }  
  115.     }  
  116.       
  117.     /**  
  118.      * 删除实例  
  119.      *   
  120.      * @param t  
  121.      * @throws HibernateException  
  122.      */  
  123.     public void delete(T t) throws HibernateException{  
  124.         Session session=null;  
  125.         try {  
  126.             session=sessionFactory.openSession();  
  127.             session.beginTransaction();  
  128.             session.delete(t);  
  129.             session.getTransaction().commit();  
  130.         } catch (HibernateException e) {  
  131.             e.printStackTrace();  
  132.             throw new HibernateException(e);  
  133.         }finally{  
  134.             session.close();  
  135.         }  
  136.     }  
  137.     /**  
  138.      * 获取实例  
  139.      *   
  140.      * @param id  
  141.      * @throws HibernateException  
  142.      */  
  143.     @SuppressWarnings("unchecked")  
  144.     public T get(Serializable id) throws Exception{  
  145.         Session session=null;  
  146.         T t=null;  
  147.         try {  
  148.             session=sessionFactory.openSession();  
  149.             session.beginTransaction();  
  150.             t=(T) session.get(getEntityClass(), id);  
  151.             session.getTransaction().commit();  
  152.         } catch (HibernateException e) {  
  153.             e.printStackTrace();  
  154.             throw new HibernateException(e);  
  155.         }finally{  
  156.             session.close();  
  157.         }  
  158.         return t;  
  159.     }  
  160.     /**  
  161.      * 查询全部  
  162.      *   
  163.      * @throws HibernateException  
  164.      */  
  165.     @SuppressWarnings("unchecked")  
  166.     public List<T> findAll() throws Exception {  
  167.         List<T> list=null;  
  168.         Session session=null;  
  169.         try {  
  170.             session = sessionFactory.openSession();  
  171.             session.beginTransaction();  
  172.             Query query = session.createQuery(HQL_LIST_ALL);  
  173.             list = query.list();  
  174.             session.getTransaction().commit();  
  175.         } catch (HibernateException e) {  
  176.             e.printStackTrace();  
  177.         }finally{  
  178.             session.close();  
  179.         }  
  180.         return list;  
  181.     }  
  182.     /**  
  183.      * 查询总数  
  184.      *   
  185.      * @throws HibernateException  
  186.      */  
  187.     public Integer findAllCount() throws Exception {  
  188.         Session session=null;  
  189.         Integer count=0;  
  190.         try {  
  191.             session = sessionFactory.openSession();  
  192.             session.beginTransaction();  
  193.             Query query = session.createQuery(HQL_COUNT_ALL);  
  194.             List<?> list = query.list();  
  195.             session.getTransaction().commit();  
  196.             if(list!=null&&!list.isEmpty()){  
  197.                 count=((Integer) list.get(0)).intValue();  
  198.             }  
  199.         } catch (HibernateException e) {  
  200.             e.printStackTrace();  
  201.         }finally{  
  202.             session.close();  
  203.         }  
  204.         return count;  
  205.     }  
  206.     /**  
  207.      * QBC查询  
  208.      *   
  209.      * @param criteria  
  210.      * @throws HibernateException  
  211.      */  
  212.     @SuppressWarnings("unchecked")  
  213.     public List<T> findByCriteria(Criteria criteria) throws Exception {  
  214.         List<T> list=null;  
  215.         Session session=null;  
  216.         try {  
  217.             session = sessionFactory.openSession();  
  218.             session.beginTransaction();  
  219.             Criteria criteria1 = session.createCriteria(getEntityClass());  
  220.             criteria1=criteria;  
  221.             list = criteria1.list();  
  222.             session.getTransaction().commit();  
  223.         } catch (HibernateException e) {  
  224.             e.printStackTrace();  
  225.         }finally{  
  226.             session.close();  
  227.         }  
  228.         return list;  
  229.     }  
  230.       
  231.     /**  
  232.      * QBE查询  
  233.      *   
  234.      * @param t  
  235.      * @throws HibernateException  
  236.      */  
  237.     @SuppressWarnings("unchecked")  
  238.     public List<T> findByExample(T t) throws Exception {  
  239.         List<T> list=null;  
  240.         Session session=null;  
  241.         Example example = Example.create(t);  
  242.         try {  
  243.             session = sessionFactory.openSession();  
  244.             session.beginTransaction();  
  245.             Criteria criteria = session.createCriteria(getEntityClass());  
  246.             criteria.add(example);  
  247.             list = criteria.list();  
  248.             session.getTransaction().commit();  
  249.         } catch (HibernateException e) {  
  250.             e.printStackTrace();  
  251.         }finally{  
  252.             session.close();  
  253.         }  
  254.         return list;  
  255.     }  
  256.     /**  
  257.      * HQL查询  
  258.      *   
  259.      * @param hql  
  260.      * @param objects  
  261.      * @throws HibernateException  
  262.      */  
  263.     @SuppressWarnings("unchecked")  
  264.     public List<Object[]> findByHql(String hql,final Object...objects) throws Exception{  
  265.         List<Object[]> list=null;  
  266.         Session session=null;  
  267.         try {  
  268.             session=sessionFactory.openSession();  
  269.             session.beginTransaction();  
  270.             Query query = session.createQuery(hql);  
  271.             for (int i = 0; i < objects.length; i++) {  
  272.                 query.setParameter(i, objects[i]);  
  273.             }  
  274.             list = query.list();  
  275.             session.getTransaction().commit();  
  276.         } catch (Exception e) {  
  277.             e.printStackTrace();  
  278.         }finally{  
  279.             session.close();  
  280.         }  
  281.         return list;  
  282.     }  
  283.     /**  
  284.      * SQL查询  
  285.      *   
  286.      * @param hql  
  287.      * @param objects  
  288.      * @throws HibernateException  
  289.      */  
  290.     @SuppressWarnings("unchecked")  
  291.     public List<Object[]> findBySql(String sql,final Object...objects){  
  292.         List<Object[]> list=null;  
  293.         Session session=null;  
  294.         try {  
  295.             session=sessionFactory.openSession();  
  296.             session.beginTransaction();  
  297.             Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);  
  298.             for (int i = 0; i < objects.length; i++) {  
  299.                 query.setParameter(i, objects[i]);  
  300.             }  
  301.             list = query.list();  
  302.             session.getTransaction().commit();  
  303.         } catch (Exception e) {  
  304.             e.printStackTrace();  
  305.         }finally{  
  306.             session.close();  
  307.         }  
  308.         return list;  
  309.     }  
  310. }  


BaseService

  1. package com.sshFrame.zero.service;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import com.sshFrame.zero.dao.BaseDao;  
  7. /**  
  8.  * @author 雪精灵  
  9.  *  
  10.  * @param <t>  
  11.  */  
  12.   
  13. public class BaseService<T extends Serializable> {  
  14.       
  15.     protected BaseDao<T> baseDao;  
  16.       
  17.     public void save(T t) throws Exception{  
  18.         baseDao.save(t);  
  19.     }  
  20.     public void update(T t) throws Exception{  
  21.         baseDao.update(t);  
  22.     }  
  23.     public void delete(T t) throws Exception{  
  24.         baseDao.delete(t);  
  25.     }  
  26.     public T get(Serializable id) throws Exception{  
  27.         return baseDao.get(id);  
  28.     }  
  29.     public List<T> findAll() throws Exception{  
  30.         return baseDao.findAll();  
  31.     }  
  32.     public List<T> findByExample(T t) throws Exception{  
  33.         return baseDao.findByExample(t);  
  34.     }  
  35.     public BaseDao<T> getBaseDao() {  
  36.         return baseDao;  
  37.     }  
  38.     public void setBaseDao(BaseDao<T> baseDao) {  
  39.         this.baseDao = baseDao;  
  40.     }  
  41. }</t>  

 

四、写7个pojo

  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Column;  
  9. import javax.persistence.Entity;  
  10. import javax.persistence.FetchType;  
  11. import javax.persistence.GeneratedValue;  
  12. import javax.persistence.Id;  
  13. import javax.persistence.OneToMany;  
  14. import javax.persistence.Table;  
  15.   
  16. import org.hibernate.annotations.GenericGenerator;  
  17.   
  18. @Entity  
  19. @Table(name="userinfo")  
  20. public class Userinfo implements Serializable{  
  21.     private static final long serialVersionUID = 1L;  
  22.     private String userid;  
  23.     private String username;  
  24.     private String password;  
  25.     private String depid;  
  26.     private String dutyid;  
  27.     private Set<Userrole> userroles=new HashSet<Userrole>();  
  28.     @GenericGenerator(name = "generator"strategy = "uuid")  
  29.     @Id  
  30.     @GeneratedValue(generator = "generator")  
  31.     @Column(name = "userid"unique = truenullable = falselength = 50)  
  32.     public String getUserid() {  
  33.         return userid;  
  34.     }  
  35.     public void setUserid(String userid) {  
  36.         this.userid = userid;  
  37.     }  
  38.     @Column(name = "username"nullable = falselength = 50)  
  39.     public String getUsername() {  
  40.         return username;  
  41.     }  
  42.     public void setUsername(String username) {  
  43.         this.username = username;  
  44.     }  
  45.     @Column(name = "password"nullable = falselength = 50)  
  46.     public String getPassword() {  
  47.         return password;  
  48.     }  
  49.     public void setPassword(String password) {  
  50.         this.password = password;  
  51.     }  
  52.     @Column(name = "depid"nullable = falselength = 50)  
  53.     public String getDepid() {  
  54.         return depid;  
  55.     }  
  56.     public void setDepid(String depid) {  
  57.         this.depid = depid;  
  58.     }  
  59.     @Column(name = "dutyid"nullable = falselength = 50)  
  60.     public String getDutyid() {  
  61.         return dutyid;  
  62.     }  
  63.     public void setDutyid(String dutyid) {  
  64.         this.dutyid = dutyid;  
  65.     }  
  66.     @OneToMany(cascade=CascadeType.REMOVE,mappedBy="userinfo",fetch=FetchType.LAZY)  
  67.     public Set<Userrole> getUserroles() {  
  68.         return userroles;  
  69.     }  
  70.     public void setUserroles(Set<Userrole> userroles) {  
  71.         this.userroles = userroles;  
  72.     }  
  73. }  
  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Column;  
  9. import javax.persistence.Entity;  
  10. import javax.persistence.FetchType;  
  11. import javax.persistence.GeneratedValue;  
  12. import javax.persistence.Id;  
  13. import javax.persistence.OneToMany;  
  14. import javax.persistence.Table;  
  15.   
  16. import org.hibernate.annotations.GenericGenerator;  
  17.   
  18.   
  19. @Entity  
  20. @Table(name="role")  
  21. public class Role implements Serializable{  
  22.     private static final long serialVersionUID = 1L;  
  23.     private String id;  
  24.     private String name;  
  25.     private Set<Userrole> userroles=new HashSet<Userrole>();  
  26.     private Set<Rolerights> rolerights=new HashSet<Rolerights>();  
  27.     @GenericGenerator(name = "generator"strategy = "uuid")  
  28.     @Id  
  29.     @GeneratedValue(generator = "generator")  
  30.     @Column(name = "id"unique = truenullable = falselength = 50)  
  31.     public String getId() {  
  32.         return id;  
  33.     }  
  34.     public void setId(String id) {  
  35.         this.id = id;  
  36.     }  
  37.     @Column(name = "name"nullable = falselength = 50)  
  38.     public String getName() {  
  39.         return name;  
  40.     }  
  41.     public void setName(String name) {  
  42.         this.name = name;  
  43.     }  
  44.     @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="role")  
  45.     public Set<Userrole> getUserroles() {  
  46.         return userroles;  
  47.     }  
  48.     public void setUserroles(Set<Userrole> userroles) {  
  49.         this.userroles = userroles;  
  50.     }  
  51.     @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="role")  
  52.     public Set<Rolerights> getRolerights() {  
  53.         return rolerights;  
  54.     }  
  55.     public void setRolerights(Set<Rolerights> rolerights) {  
  56.         this.rolerights = rolerights;  
  57.     }  
  58. }  


  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Column;  
  9. import javax.persistence.Entity;  
  10. import javax.persistence.FetchType;  
  11. import javax.persistence.GeneratedValue;  
  12. import javax.persistence.Id;  
  13. import javax.persistence.OneToMany;  
  14. import javax.persistence.Table;  
  15.   
  16. import org.hibernate.annotations.GenericGenerator;  
  17. @Entity  
  18. @Table(name="rights")  
  19. public class Rights implements Serializable{  
  20.   
  21.     private static final long serialVersionUID = 1L;  
  22.     private String id;  
  23.     private String name;  
  24.     private Set<Rolerights> rolerights=new HashSet<Rolerights>();  
  25.     @GenericGenerator(name = "generator"strategy = "uuid")  
  26.     @Id  
  27.     @GeneratedValue(generator = "generator")  
  28.     @Column(name = "id"unique = truenullable = falselength = 50)  
  29.     public String getId() {  
  30.         return id;  
  31.     }  
  32.     public void setId(String id) {  
  33.         this.id = id;  
  34.     }  
  35.     public String getName() {  
  36.         return name;  
  37.     }  
  38.     @Column(name = "name"nullable = falselength = 50)  
  39.     public void setName(String name) {  
  40.         this.name = name;  
  41.     }  
  42.     @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="rights")  
  43.     public Set<Rolerights> getRolerights() {  
  44.         return rolerights;  
  45.     }  
  46.     public void setRolerights(Set<Rolerights> rolerights) {  
  47.         this.rolerights = rolerights;  
  48.     }  
  49. }  

 

  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Column;  
  9. import javax.persistence.Entity;  
  10. import javax.persistence.FetchType;  
  11. import javax.persistence.GeneratedValue;  
  12. import javax.persistence.Id;  
  13. import javax.persistence.OneToMany;  
  14. import javax.persistence.Table;  
  15.   
  16. import org.hibernate.annotations.GenericGenerator;  
  17. @Entity  
  18. @Table(name="resources")  
  19. public class Resources implements Serializable{  
  20.   
  21.     private static final long serialVersionUID = 1L;  
  22.     private String id;  
  23.     private String name;  
  24.     private String url;  
  25.     private Set<Rightsresources> rightsresourcs=new HashSet<Rightsresources>();  
  26.     @GenericGenerator(name = "generator"strategy = "uuid")  
  27.     @Id  
  28.     @GeneratedValue(generator = "generator")  
  29.     @Column(name = "id"unique = truenullable = falselength = 50)  
  30.     public String getId() {  
  31.         return id;  
  32.     }  
  33.     public void setId(String id) {  
  34.         this.id = id;  
  35.     }  
  36.     @Column(name = "name"nullable = falselength = 50)  
  37.     public String getName() {  
  38.         return name;  
  39.     }  
  40.     public void setName(String name) {  
  41.         this.name = name;  
  42.     }  
  43.     @Column(name = "url"nullable = falselength = 100)  
  44.     public String getUrl() {  
  45.         return url;  
  46.     }  
  47.     public void setUrl(String url) {  
  48.         this.url = url;  
  49.     }  
  50.     @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="resources")  
  51.     public Set<Rightsresources> getRightsresourcs() {  
  52.         return rightsresourcs;  
  53.     }  
  54.     public void setRightsresourcs(Set<Rightsresources> rightsresourcs) {  
  55.         this.rightsresourcs = rightsresourcs;  
  56.     }  
  57.       
  58. }  

 

  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.FetchType;  
  8. import javax.persistence.GeneratedValue;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.ManyToOne;  
  12. import javax.persistence.Table;  
  13.   
  14. import org.hibernate.annotations.GenericGenerator;  
  15.   
  16. @Entity  
  17. @Table(name="userrole")  
  18. public class Userrole implements Serializable{  
  19.     private static final long serialVersionUID = 1L;  
  20.     private String id;  
  21.     private Userinfo userinfo;  
  22.     private Role role;  
  23.     @GenericGenerator(name = "generator"strategy = "uuid")  
  24.     @Id  
  25.     @GeneratedValue(generator = "generator")  
  26.     @Column(name = "id"unique = truenullable = falselength = 50)  
  27.     public String getId() {  
  28.         return id;  
  29.     }  
  30.     public void setId(String id) {  
  31.         this.id = id;  
  32.     }  
  33.     @ManyToOne(fetch=FetchType.LAZY)  
  34.     @JoinColumn(name="userid")  
  35.     public Userinfo getUserinfo() {  
  36.         return userinfo;  
  37.     }  
  38.     public void setUserinfo(Userinfo userinfo) {  
  39.         this.userinfo = userinfo;  
  40.     }  
  41.     @ManyToOne(fetch=FetchType.LAZY)  
  42.     @JoinColumn(name="roleid")  
  43.     public Role getRole() {  
  44.         return role;  
  45.     }  
  46.     public void setRole(Role role) {  
  47.         this.role = role;  
  48.     }  
  49. }  

 

  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.FetchType;  
  8. import javax.persistence.GeneratedValue;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.ManyToOne;  
  12. import javax.persistence.Table;  
  13.   
  14. import org.hibernate.annotations.GenericGenerator;  
  15.   
  16. @Entity  
  17. @Table(name="rolerights")  
  18. public class Rolerights implements Serializable{  
  19.     private static final long serialVersionUID = 1L;  
  20.     private String id;  
  21.     private Role role;  
  22.     private Rights rights;  
  23.     @GenericGenerator(name = "generator"strategy = "uuid")  
  24.     @Id  
  25.     @GeneratedValue(generator = "generator")  
  26.     @Column(name = "id"unique = truenullable = falselength = 50)  
  27.     public String getId() {  
  28.         return id;  
  29.     }  
  30.     public void setId(String id) {  
  31.         this.id = id;  
  32.     }  
  33.     @ManyToOne(fetch=FetchType.LAZY)  
  34.     @JoinColumn(name="roleid")  
  35.     public Role getRole() {  
  36.         return role;  
  37.     }  
  38.     public void setRole(Role role) {  
  39.         this.role = role;  
  40.     }  
  41.     @ManyToOne(fetch=FetchType.LAZY)  
  42.     @JoinColumn(name="rightsid")  
  43.     public Rights getRights() {  
  44.         return rights;  
  45.     }  
  46.     public void setRights(Rights rights) {  
  47.         this.rights = rights;  
  48.     }  
  49. }  

 

  1. package com.sshFrame.zero.pojo;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.FetchType;  
  8. import javax.persistence.GeneratedValue;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.ManyToOne;  
  12. import javax.persistence.Table;  
  13.   
  14. import org.hibernate.annotations.GenericGenerator;  
  15. @Entity  
  16. @Table(name="rightsresources")  
  17. public class Rightsresources implements Serializable{  
  18.   
  19.     private static final long serialVersionUID = 1L;  
  20.     private String id;  
  21.     private Rights rights;  
  22.     private Resources resources;  
  23.     @GenericGenerator(name = "generator"strategy = "uuid")  
  24.     @Id  
  25.     @GeneratedValue(generator = "generator")  
  26.     @Column(name = "id"unique = truenullable = falselength = 50)  
  27.     public String getId() {  
  28.         return id;  
  29.     }  
  30.     public void setId(String id) {  
  31.         this.id = id;  
  32.     }  
  33.     @ManyToOne(fetch=FetchType.LAZY)  
  34.     @JoinColumn(name="rightsid")  
  35.     public Rights getRights() {  
  36.         return rights;  
  37.     }  
  38.     public void setRights(Rights rights) {  
  39.         this.rights = rights;  
  40.     }  
  41.     @ManyToOne(fetch=FetchType.LAZY)  
  42.     @JoinColumn(name="resourcesid")  
  43.     public Resources getResources() {  
  44.         return resources;  
  45.     }  
  46.     public void setResources(Resources resources) {  
  47.         this.resources = resources;  
  48.     }  
  49.       
  50. }  

五、写各个Service和Action

UserinfoService 这个一定要注意,要在setUserinfoDao方法里把当前的dao给basedao,否则,basedao会报空指针

  1. package com.sshFrame.zero.service.users;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Component;  
  7. import org.springframework.stereotype.Service;  
  8.   
  9. import com.sshFrame.zero.dao.users.UserinfoDao;  
  10. import com.sshFrame.zero.pojo.Userinfo;  
  11. import com.sshFrame.zero.service.BaseService;  
  12. /**  
  13.  * 用户管理  
  14.  * @author 雪精灵  
  15.  *  
  16.  * @param <t>  
  17.  */  
  18.   
  19. @Service  
  20. @Component("userinfoService")  
  21. public class UserinfoService extends BaseService<Userinfo>{  
  22.     private UserinfoDao userinfoDao;  
  23.     public UserinfoService() {  
  24.         super();  
  25.     }  
  26.     public Userinfo findlogin(String username,String password) throws Exception{  
  27.         Userinfo userinfo=new Userinfo();  
  28.         userinfo.setUsername(username);  
  29.         userinfo.setPassword(password);  
  30.         List<Userinfo> userinfos = findByExample(userinfo);  
  31.         if(userinfos!=null&&!userinfos.isEmpty()){  
  32.             userinfo=userinfos.get(0);  
  33.         }else{  
  34.             userinfo=null;  
  35.         }  
  36.         return userinfo;  
  37.     }  
  38.     public List<?> used(String userid,String url) throws Exception {  
  39.         String hql="select ur.userinfo.userid,re.name,re.url from Userrole ur,Role r,Rolerights rr,Rights ri,Rightsresources rs,Resources re "+  
  40.             "where ur.role.id=r.id and r.id=rr.role.id and rr.rights.id=ri.id and ri.id=rs.rights.id and rs.resources.id=re.id and "+  
  41.             "ur.userinfo.userid=? and re.url=?";  
  42.         List<?> userResource = userinfoDao.findByHql(hql,userid,url);  
  43.         return userResource;  
  44.     }  
  45.     public UserinfoDao getUserinfoDao() {  
  46.         return userinfoDao;  
  47.     }  
  48.     /**  
  49.      * 一定要用set方法注入,并赋值给baseDao,否则baseDao为null;  
  50.      * 只适用于注入一个Dao  
  51.      * @param userinfoDao  
  52.      */  
  53.     @Autowired  
  54.     public void setUserinfoDao(UserinfoDao userinfoDao) {  
  55.         super.setBaseDao(userinfoDao);  
  56.         this.userinfoDao = userinfoDao;  
  57.     }  
  58. }  
  59.  </t>  
  1. package com.sshFrame.zero.action.users;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.apache.struts2.convention.annotation.Action;  
  9. import org.apache.struts2.convention.annotation.Namespace;  
  10. import org.apache.struts2.convention.annotation.Result;  
  11. import org.apache.struts2.interceptor.ServletRequestAware;  
  12. import org.apache.struts2.interceptor.ServletResponseAware;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.context.annotation.Scope;  
  15. import org.springframework.stereotype.Component;  
  16.   
  17. import com.opensymphony.xwork2.ActionSupport;  
  18. import com.sshFrame.zero.pojo.Userinfo;  
  19. import com.sshFrame.zero.service.users.UserinfoService;  
  20. /**  
  21.  * @author 雪精灵  
  22.  *  
  23.  *   
  24.  */  
  25. @Namespace("/")  
  26. @Scope("prototype")  
  27. @Component("userinfoAction")  
  28. public class UserinfoAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{  
  29.     private static final long serialVersionUID = 1L;  
  30.     private HttpServletRequest request;  
  31.     private HttpServletResponse response;  
  32.     @Autowired  
  33.     private UserinfoService userinfoService;  
  34.     @Action(value="login",results={  
  35.             @Result(name="success",location="init.jsp"),  
  36.             @Result(name="failure",location="/index.jsp")  
  37.     })  
  38.     public String login(){  
  39.         String username=request.getParameter("username");  
  40.         String password=request.getParameter("password");  
  41.         Userinfo userinfo=null;  
  42.         try {  
  43.             userinfo = userinfoService.findlogin(username, password);  
  44.         } catch (Exception e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.         if(userinfo==null){  
  48.             request.setAttribute("msg", "用户名或密码错误");  
  49.             return "failure";  
  50.         }else{  
  51.             request.getSession().setAttribute("userid", userinfo.getUserid());  
  52.         }  
  53.         return "success";  
  54.     }  
  55.     public boolean used(String userid,String url) {  
  56.         List<?> list=null;  
  57.         try {  
  58.             list = userinfoService.used(userid, url);  
  59.         } catch (Exception e) {  
  60.             e.printStackTrace();  
  61.             return false;  
  62.         }  
  63.         if(list!=null&&!list.isEmpty()){  
  64.             return true;  
  65.         }  
  66.         return false;  
  67.     }  
  68.     @Override  
  69.     public void setServletResponse(HttpServletResponse response) {  
  70.         this.response=response;  
  71.     }  
  72.     @Override  
  73.     public void setServletRequest(HttpServletRequest request) {  
  74.         this.request=request;  
  75.     }  
  76.     public UserinfoService getUserinfoService() {  
  77.         return userinfoService;  
  78.     }  
  79.     public void setUserinfoService(UserinfoService userinfoService) {  
  80.         this.userinfoService = userinfoService;  
  81.     }  
  82. }  
  1. package com.sshFrame.zero.action.users;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.struts2.convention.annotation.Action;  
  7. import org.apache.struts2.convention.annotation.Namespace;  
  8. import org.apache.struts2.convention.annotation.ParentPackage;  
  9. import org.apache.struts2.convention.annotation.Result;  
  10. import org.apache.struts2.interceptor.ServletRequestAware;  
  11. import org.apache.struts2.interceptor.ServletResponseAware;  
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.context.annotation.Scope;  
  14.   
  15. import com.opensymphony.xwork2.ActionSupport;  
  16. import com.sshFrame.zero.service.users.UserinfoService;  
  17. /**  
  18.  * @author 雪精灵  
  19.  *  
  20.  *   
  21.  */  
  22. @Namespace("/admin")  
  23. @ParentPackage("default")  
  24. @Scope("prototype")  
  25. public class AdminAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{  
  26.     private static final long serialVersionUID = 1L;  
  27.     @Autowired  
  28.     private UserinfoService userinfoService;  
  29.     private HttpServletRequest request;  
  30.     private HttpServletResponse response;  
  31.     @Action(value="init",results={@Result(name="success",location="main.jsp"),  
  32.             @Result(name="failure",location="/index.jsp")})  
  33.     public String init(){  
  34.         String userid=(String) request.getSession().getAttribute("userid");  
  35.         System.out.println(userid);  
  36.         return SUCCESS;  
  37.     }  
  38.     public UserinfoService getUserinfoService() {  
  39.         return userinfoService;  
  40.     }  
  41.     public void setUserinfoService(UserinfoService userinfoService) {  
  42.         this.userinfoService = userinfoService;  
  43.     }  
  44.     @Override  
  45.     public void setServletResponse(HttpServletResponse response) {  
  46.         this.response=response;  
  47.     }  
  48.     @Override  
  49.     public void setServletRequest(HttpServletRequest request) {  
  50.         this.request=request;  
  51.     }  
  52. }  


六、加入拦截器

  1. package com.sshFrame.zero.interceptor;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.apache.struts2.ServletActionContext;  
  6.   
  7. import com.opensymphony.xwork2.Action;  
  8. import com.opensymphony.xwork2.ActionInvocation;  
  9. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
  10. import com.sshFrame.zero.action.users.UserinfoAction;  
  11. import com.sshFrame.zero.exception.AhCustomException;  
  12. import com.sshFrame.zero.exception.AhCustomException.ExcCode;  
  13.   
  14. /**  
  15.  * 用户权限拦截器,在struts.xml中配置  
  16.  * @author 雪精灵  
  17.  */  
  18. public class AuthorityInterceptor extends AbstractInterceptor{  
  19.   
  20.     private static final long serialVersionUID = 2914081148619842225L;  
  21.     private UserinfoAction userinfoAction;  
  22.     @Override  
  23.     public String intercept(ActionInvocation invocation) throws Exception {  
  24.         HttpServletRequest request = ServletActionContext.getRequest();  
  25. //      String method = invocation.getProxy().getMethod();  
  26. //      String actionName=invocation.getInvocationContext().getName();  
  27.         String userid = (String) request.getSession().getAttribute("userid");  
  28.         if(userid==null||"".equals(userid)){  
  29.             request.setAttribute("msg",AhCustomException.getExcMessage(ExcCode.Unlogined));  
  30.             return Action.ERROR;  
  31.         }  
  32.         //获取项目路径  
  33.         String contextPath=request.getServletContext().getContextPath();  
  34.         //获取当前路径  
  35.         String uri = request.getRequestURI();  
  36.         //当前相对项目的路径  
  37.         String actionUrl=uri.replace(contextPath, "");  
  38.         boolean used = userinfoAction.used(userid, actionUrl);  
  39.         if(used){  
  40.             return invocation.invoke();  
  41.         }else{  
  42.             request.setAttribute("msg",AhCustomException.getExcMessage(ExcCode.InvalidRights));  
  43.             return Action.ERROR;  
  44.         }  
  45.     }  
  46.     public UserinfoAction getUserinfoAction() {  
  47.         return userinfoAction;  
  48.     }  
  49.     public void setUserinfoAction(UserinfoAction userinfoAction) {  
  50.         this.userinfoAction = userinfoAction;  
  51.     }  
  52.   
  53. }  

 

  1. package com.sshFrame.zero.interceptor;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.apache.log4j.Logger;  
  6. import org.apache.struts2.ServletActionContext;  
  7. import org.hibernate.HibernateException;  
  8.   
  9. import com.opensymphony.xwork2.Action;  
  10. import com.opensymphony.xwork2.ActionInvocation;  
  11. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
  12. import com.sshFrame.zero.exception.AhCustomException;  
  13. import com.sshFrame.zero.exception.AhCustomException.ExcCode;  
  14.   
  15. /**  
  16.  * 错误权限拦截器,在struts.xml中配置  
  17.  * @author 雪精灵  
  18.  */  
  19. public class ExceptionInterceptor extends AbstractInterceptor{  
  20.     private Logger logger=Logger.getLogger(ExceptionInterceptor.class);  
  21.     private static final long serialVersionUID = -3490533736557683231L;  
  22.     private String excMessage="";  
  23.     @Override  
  24.     public String intercept(ActionInvocation invocation) throws Exception {  
  25.         String result;  
  26.         HttpServletRequest request = ServletActionContext.getRequest();  
  27.         String uri = request.getRequestURI();  
  28.         try {  
  29.             result = invocation.invoke();  
  30.         } catch (HibernateException e) {  
  31.             e.printStackTrace();  
  32.             logger.error("异常拦截器拦截到异常:"+"<br/>"+"uri为:"+uri+"<br/>"+e);  
  33.             excMessage=AhCustomException.getExcMessage(ExcCode.DataProcessing);  
  34.             request.setAttribute("msg", excMessage);  
  35.             result=Action.ERROR;  
  36.         }catch (NullPointerException e) {  
  37.             e.printStackTrace();  
  38.             logger.error("异常拦截器拦截到异常:"+"<br/>"+"action的名称为:"+uri+"<br/>"+e);  
  39.             excMessage=AhCustomException.getExcMessage(ExcCode.IllegalData);  
  40.             request.setAttribute("msg", excMessage);  
  41.             result=Action.ERROR;  
  42.         }catch (AhCustomException e) {  
  43.             e.printStackTrace();  
  44.             logger.error("异常拦截器拦截到异常:"+"<br/>"+"action的名称为:"+uri+"<br/>"+e);  
  45.             excMessage=e.getExcMessage();  
  46.             request.setAttribute("msg", excMessage);  
  47.             result=Action.ERROR;  
  48.         }catch (Exception e) {  
  49.             e.printStackTrace();  
  50.             logger.error("异常拦截器拦截到异常:"+"<br/>"+"action的名称为:"+uri+"<br/>"+e);  
  51.             excMessage=AhCustomException.getExcMessage(ExcCode.AppError);  
  52.             request.setAttribute("msg", excMessage);  
  53.             result=Action.ERROR;  
  54.         }  
  55.         return result;  
  56.     }  
  57.   
  58. }  

七、自定义异常类

  1. package com.sshFrame.zero.exception;  
  2. /**  
  3.  * 自定义异常处理  
  4.  * @author 雪精灵  
  5.  */  
  6. public class AhCustomException extends Exception{  
  7.   
  8.     private static final long serialVersionUID = 1L;  
  9.    /**  
  10.      * 错误类型标识  
  11.      */  
  12.     private ExcCode excCode = null;  
  13.     public enum ExcCode{  
  14.         AppError,  
  15.         InvalidRights,  
  16.         IllegalData,  
  17.         DataProcessing,   
  18.         Unlogined  
  19.     }  
  20.     public static final String[] excMessage = {  
  21.         "内部异常",  
  22.         "您没有执行本操作的权限",  
  23.         "提供的数据为空或不合法",  
  24.         "数据处理异常",  
  25.         "您可能还没有登录本系统,或者已经超时,您必须先登录本系统后才能使用该功能<p><a href='../' target='_parent'>重新登录</a></p>"  
  26.     };  
  27.     public AhCustomException(){  
  28.          super(getExcMessage(ExcCode.AppError));  
  29.          excCode = ExcCode.AppError;  
  30.     }  
  31.       
  32.     /**  
  33.      * 构造函数  
  34.      *   
  35.      * @param arg0  
  36.      *            错误类型标识  
  37.      */  
  38.     public AhCustomException(ExcCode excCode) {  
  39.         super(getExcMessage(excCode));  
  40.         this.excCode = excCode;  
  41.     }  
  42.     /**  
  43.      * 根据错误类型标识获取错误信息  
  44.      *   
  45.      * @param emFlag  
  46.      *            错误类型标识  
  47.      *   
  48.      * @return 错误信息  
  49.      */  
  50.     public static String getExcMessage(ExcCode excCode) {  
  51.         return excMessage[excCode.ordinal()];  
  52.     }  
  53.       
  54.     public String getExcMessage() {  
  55.         return excMessage[excCode.ordinal()];  
  56.     }  
  57.      /**  
  58.      * 构造函数  
  59.      *   
  60.      * @param arg0  
  61.      *            错误类型标识  
  62.      *              
  63.      * @param arg1  
  64.      *            被包含的异常对象  
  65.      */  
  66.     public AhCustomException(ExcCode excCode, Throwable throwable) {  
  67.         super(getExcMessage(excCode), throwable);  
  68.         setStackTrace(throwable.getStackTrace());  
  69.         this.excCode = excCode;  
  70.     }  
  71.     /**  
  72.      * 构造函数  
  73.      *   
  74.      * @param arg0  
  75.      *            被包含的异常对象  
  76.      */  
  77.     public AhCustomException(Throwable throwable) {  
  78.         super(getExcMessage(throwable.getClass() == AhCustomException.class ? ((AhCustomException) throwable).excCode : ExcCode.AppError), throwable);  
  79.         setStackTrace(throwable.getStackTrace());  
  80.         if (throwable.getClass() == AhCustomException.class)  
  81.             excCode = ((AhCustomException) throwable).excCode;  
  82.         else  
  83.             excCode = excCode.AppError;  
  84.     }  
  85.   
  86. }  

八、页面

index.jsp,在webContent下

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.   ${msg }  
  25.   <form action="login" method="post">  
  26.    <table>  
  27.     <tbody>  
  28.         <tr><td>用户名:</td><td><input type="text" name="username"/></td></tr>  
  29.         <tr><td>密码:</td><td><input type="password" name="password"/></td></tr>  
  30.         <tr><td colspan="2"><input type="submit" value="Login"/></td></tr>  
  31.     </tbody>  
  32.    </table>  
  33.    </form>  
  34.   </body>  
  35. </html>  


init.jsp.在web-inf/content/下

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'init.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.     <script type="text/javascript">  
  22.     window.onload=function(){  
  23.         window.location.href="admin/init";  
  24.     }  
  25.     </script>  
  26.   </head>  
  27.   <body>  
  28.     欢迎进入  
  29.   </body>  
  30. </html>  

程序下载链接:http://download.csdn.net/detail/doublelucklysnow/5001504

网友评论

登录后评论
0/500
评论