Posted by & filed under Uncategorized.

About chen xiang

Xiang Chen has written 52 post in this blog.

先做准备工作:

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. <!– hibernate 懒加载的问题过滤 ,可以不配置 –>
  11.   <filter>
  12.     <description>hibernate Session 过滤器</description>
  13.     <filter-name>openSessionInViewFilter</filter-name>
  14.     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  15.   </filter>
  16.   <filter-mapping>
  17.     <filter-name>openSessionInViewFilter</filter-name>
  18.     <url-pattern>/*</url-pattern>
  19.   </filter-mapping>
  20.   <filter>
  21.  <!– struts配置 –>
  22.     <filter-name>struts2</filter-name>
  23.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  24.   </filter>
  25.   <filter-mapping>
  26.     <filter-name>struts2</filter-name>
  27.     <url-pattern>/*</url-pattern>
  28.   </filter-mapping>

struts.xml配置

  1. <struts>
  2. <!– 使用Spring –>
  3.  <constant name=”struts.objectFactory” value=”spring” />
  4.  <constant name=”struts.devMode” value=”true” />
  5.  <constant name=”struts.configuration.xml.reload” value=”true” />
  6.  <package name=”default” extends=”struts-default” namespace=”/”>
  7.   <interceptors>
  8.    <!– 使用权限拦截 –>
  9.    <interceptor name=”authority” class=”com.sshFrame.zero.interceptor.AuthorityInterceptor”/>
  10.    <!– 异常拦截 –>
  11.    <interceptor name=”exceptionInterceptor” class=”com.sshFrame.zero.interceptor.ExceptionInterceptor”/>
  12.    <!– 解决struts安全漏洞,拦截所有的带有#号的url –>
  13.    <interceptor-stack name=”baseStack”>
  14.     <interceptor-ref name=”authority”/>
  15.     <interceptor-ref name=”exceptionInterceptor”/>
  16.     <interceptor-ref name=”params”>
  17.      <param name=”excludeParams”>.*\\u0023.*</param>
  18.     </interceptor-ref>
  19.     <interceptor-ref name=”defaultStack”/>
  20.    </interceptor-stack>
  21.   </interceptors>
  22.   <!– 配置默认拦截器栈 –>
  23.   <default-interceptor-ref name=”baseStack”/>
  24.   <global-results>
  25.    <result name=”login”>/index.jsp</result>
  26.    <result name=”error”>/error.jsp</result>
  27.   </global-results>
  28.  </package>
  29. </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.     <bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource”>
  18.         <property name=”driverClassName” value=”com.mysql.jdbc.Driver”></property>
  19.         <property name=”url” value=”jdbc:mysql://127.0.0.1:3306/osdesignaid”></property>
  20.         <property name=”username” value=”root”></property>
  21.         <property name=”password” value=”root”></property>
  22.     </bean>
  23.     <bean id=”sessionFactory”
  24.         class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
  25.         <property name=”dataSource” ref=”dataSource” />
  26.         <property name=”hibernateProperties”>
  27.             <props>
  28.                 <prop key=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</prop>
  29.                 <prop key=”hibernate.current_session_context_class”>thread</prop>
  30.                 <prop key=”hibernate.cache.region.factory_class”>org.hibernate.cache.EhCacheRegionFactory</prop>
  31.                 <prop key=”hibernate.show_sql”>true</prop>
  32.                 <prop key=”hibernate.format_sql”>true</prop>
  33.                 <prop key=”hibernate.hbm2ddl.auto”>update</prop>
  34.             </props>
  35.         </property>
  36.         <property name=”packagesToScan”>
  37.             <list>
  38.                 <value>com.sshFrame.zero.pojo</value>
  39.                 <value>com.sshFrame.test.pojo</value>
  40.                 </list>
  41.         </property>
  42.     </bean>
  43.     <aop:aspectj-autoproxy /><!– 代理 –>
  44.     <!– 定义事务管理器 –>
  45.     <bean id=”txManager”  class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
  46.         <property name=”sessionFactory” ref=”sessionFactory” />
  47.     </bean>
  48.     <!– 申明annotation 加载事务驱动 –>
  49.     <tx:annotation-driven transaction-manager=”txManager” proxy-target-class=”true”/>
  50.     <tx:advice id=”txAdvice” transaction-manager=”txManager”>
  51.         <tx:attributes>
  52.             <tx:method name=”save*” propagation=”REQUIRED” />
  53.             <tx:method name=”add*” propagation=”REQUIRED” />
  54.             <tx:method name=”create*” propagation=”REQUIRED” />
  55.             <tx:method name=”insert*” propagation=”REQUIRED” />
  56.             <tx:method name=”update*” propagation=”REQUIRED” />
  57.             <tx:method name=”merge*” propagation=”REQUIRED” />
  58.             <tx:method name=”del*” propagation=”REQUIRED” />
  59.             <tx:method name=”remove*” propagation=”REQUIRED” />
  60.             <tx:method name=”put*” propagation=”REQUIRED” />
  61.             <tx:method name=”use*” propagation=”REQUIRED”/>
  62.             <!–hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到–>
  63.             <tx:method name=”get*” propagation=”REQUIRED” read-only=”true” />
  64.             <tx:method name=”count*” propagation=”REQUIRED” read-only=”true” />
  65.             <tx:method name=”find*” propagation=”REQUIRED” read-only=”true” />
  66.             <tx:method name=”list*” propagation=”REQUIRED” read-only=”true” />
  67.             <tx:method name=”*” read-only=”true” />
  68.         </tx:attributes>
  69.     </tx:advice>
  70.     <aop:config expose-proxy=”true”>
  71.         <!– 只对业务逻辑层实施事务 –>
  72.         <aop:pointcut id=”txPointcut” expression=”execution(* cn.javass..service..*.*(..))” />
  73.         <aop:advisor advice-ref=”txAdvice” pointcut-ref=”txPointcut”/>
  74.     </aop:config>
  75.     <!– 自动扫描包 –>
  76.     <context:annotation-config />
  77.     <context:component-scan base-package=”com.sshFrame.zero.*,com.sshFrame.test.*” annotation-config=”true”/>
  78. </beans>

三、写框架基类

改写基本的框架类了

Basedao

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

BaseService

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

 

四、写7个pojo

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

 

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

 

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

 

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

 

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

 

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

五、写各个Service和Action

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

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

六、加入拦截器

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

 

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

七、自定义异常类

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

八、页面

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. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
  7. <html>
  8.   <head>
  9.     <base href=”<%=basePath%>”>
  10.     <title>My JSP ‘index.jsp’ starting page</title>
  11.     <meta http-equiv=”pragma” content=”no-cache”>
  12.     <meta http-equiv=”cache-control” content=”no-cache”>
  13.     <meta http-equiv=”expires” content=”0″>
  14.     <meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
  15.     <meta http-equiv=”description” content=”This is my page”>
  16.     <!–
  17.     <link rel=”stylesheet” type=”text/css” href=”styles.css”>
  18.     –>
  19.   </head>
  20.   <body>
  21.   ${msg }
  22.   <form action=”login” method=”post”>
  23.    <table>
  24.     <tbody>
  25.         <tr><td>用户名:</td><td><input type=”text” name=”username”/></td></tr>
  26.         <tr><td>密码:</td><td><input type=”password” name=”password”/></td></tr>
  27.         <tr><td colspan=”2″><input type=”submit” value=”Login”/></td></tr>
  28.     </tbody>
  29.    </table>
  30.    </form>
  31.   </body>
  32. </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. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
  7. <html>
  8.   <head>
  9.     <base href=”<%=basePath%>”>
  10.     <title>My JSP ‘init.jsp’ starting page</title>
  11.     <meta http-equiv=”pragma” content=”no-cache”>
  12.     <meta http-equiv=”cache-control” content=”no-cache”>
  13.     <meta http-equiv=”expires” content=”0″>
  14.     <meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
  15.     <meta http-equiv=”description” content=”This is my page”>
  16.     <!–
  17.     <link rel=”stylesheet” type=”text/css” href=”styles.css”>
  18.     –>
  19.     <script type=”text/javascript”>
  20.     window.onload=function(){
  21.         window.location.href=”admin/init”;
  22.     }
  23.     </script>
  24.   </head>
  25.   <body>
  26.     欢迎进入
  27.   </body>
  28. </html>

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

Leave a Reply

  • (will not be published)