---
title: "【转】ssh(struts2.3.8+spring3.2+heibernate4.1+annotation零配置"
author: "mib168"
date: "2014-01-28T15:02:55Z"
tags: []
categories: ["企业架构"]
slug: "ssh-struts2-3-8-spring3-2-heibernate4-1-annotation"
draft: false
lastmod: "2014-01-28T15:02:55Z"
id: 2009598
url: "https://mib168.iteye.com/blog/2009598"
---

先做准备工作：

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

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

3.spring3去官网下载最新版spring3开发包[http://www.springsource.org/download/community](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.1.1.jar**为struts协助开发需要的包：可以输入[http://127.0.0.1:8686/config-browser/actionNames.action](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中

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. &lt;!-- spring 配置 --&gt;
02. &lt;listener&gt;
03. &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
04. &lt;/listener&gt;
05. &lt;context-param&gt;
06. &lt;description&gt;Spring上下文&lt;/description&gt;
07. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
08. &lt;param-value&gt;classpath:applicationContext\*.xml&lt;/param-value&gt;
09. &lt;/context-param&gt;
10. &lt;!-- hibernate 懒加载的问题过滤 ,可以不配置 --&gt;
11. &lt;filter&gt;
12. &lt;description&gt;hibernate Session 过滤器&lt;/description&gt;
13. &lt;filter-name&gt;openSessionInViewFilter&lt;/filter-name&gt;
14. &lt;filter-class&gt;org.springframework.orm.hibernate4.support.OpenSessionInViewFilter&lt;/filter-class&gt;
15. &lt;/filter&gt;
16. &lt;filter-mapping&gt;
17. &lt;filter-name&gt;openSessionInViewFilter&lt;/filter-name&gt;
18. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
19. &lt;/filter-mapping&gt;
20. &lt;filter&gt;
21. &lt;!-- struts配置 --&gt;
22. &lt;filter-name&gt;struts2&lt;/filter-name&gt;
23. &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt;
24. &lt;/filter&gt;
25. &lt;filter-mapping&gt;
26. &lt;filter-name&gt;struts2&lt;/filter-name&gt;
27. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
28. &lt;/filter-mapping&gt;

struts.xml配置

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. &lt;struts&gt;
02. &lt;!-- 使用Spring --&gt;
03. &lt;constant name="struts.objectFactory" value="spring" /&gt;
04. &lt;constant name="struts.devMode" value="true" /&gt;
05. &lt;constant name="struts.configuration.xml.reload" value="true" /&gt;
06. &lt;package name="default" extends="struts-default" namespace="/"&gt;
07. &lt;interceptors&gt;
08. &lt;!-- 使用权限拦截 --&gt;
09. &lt;interceptor name="authority" class="com.sshFrame.zero.interceptor.AuthorityInterceptor"/&gt;
10. &lt;!-- 异常拦截 --&gt;
11. &lt;interceptor name="exceptionInterceptor" class="com.sshFrame.zero.interceptor.ExceptionInterceptor"/&gt;
12. &lt;!-- 解决struts安全漏洞，拦截所有的带有#号的url --&gt;
13. &lt;interceptor-stack name="baseStack"&gt;
14. &lt;interceptor-ref name="authority"/&gt;
15. &lt;interceptor-ref name="exceptionInterceptor"/&gt;
16. &lt;interceptor-ref name="params"&gt;
17. &lt;param name="excludeParams"&gt;.\*\\\\u0023.\*&lt;/param&gt;
18. &lt;/interceptor-ref&gt;
19. &lt;interceptor-ref name="defaultStack"/&gt;
20. &lt;/interceptor-stack&gt;
21. &lt;/interceptors&gt;
22. &lt;!-- 配置默认拦截器栈 --&gt;
23. &lt;default-interceptor-ref name="baseStack"/&gt;
24. &lt;global-results&gt;
25. &lt;result name="login"&gt;/index.jsp&lt;/result&gt;
26. &lt;result name="error"&gt;/error.jsp&lt;/result&gt;
27. &lt;/global-results&gt;
28. &lt;/package&gt;
29. &lt;/struts&gt;

 applicationcontext.xml配置：

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

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

配置都写好了，

改写基本的框架类了

Basedao

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

001. package com.sshFrame.zero.dao;
002. import java.io.Serializable;
003. import java.lang.reflect.Field;
004. import java.lang.reflect.ParameterizedType;
005. import java.lang.reflect.Type;
006. import java.util.List;
007. import javax.persistence.Id;
008. import org.hibernate.Criteria;
009. import org.hibernate.HibernateException;
010. import org.hibernate.Query;
011. import org.hibernate.Session;
012. import org.hibernate.SessionFactory;
013. import org.hibernate.criterion.Example;
014. import org.springframework.beans.factory.annotation.Autowired;
015. /\**
016. * 基于hibernate的BaseDao
017. * Spring3对Hibernate4已经没有了HibernateDaoSupport和HibernateTemplate的支持，使用了原生态的API
018. * @author 雪精灵
019. \*
020. * @param &lt;T&gt;
021. \*/
022. public class BaseDao&lt;T extends Serializable&gt; {
023. @Autowired
024. private SessionFactory sessionFactory;
025. //当前泛型类
026. @SuppressWarnings("rawtypes")
027. private Class entityClass;
028. //当前主键名称
029. private String pkname;
030. private final String HQL\_LIST\_ALL;
031. private final String HQL\_COUNT\_ALL;
032. @SuppressWarnings("rawtypes")
033. public Class getEntityClass() {
034. return entityClass;
035. }
036. @SuppressWarnings("rawtypes")
037. public void setEntityClass(Class entityClass) {
038. this.entityClass = entityClass;
039. }
040. @SuppressWarnings("rawtypes")
041. public BaseDao() {
042. //获取当前泛型类
043. Type type = this.getClass().getGenericSuperclass();
044. if (type.toString().indexOf("BaseDao") != -1) {
045. ParameterizedType type1 = (ParameterizedType) type;
046. Type\[] types = type1.getActualTypeArguments();
047. setEntityClass((Class) types\[0]);
048. }else{
049. type = ((Class)type).getGenericSuperclass();
050. ParameterizedType type1 = (ParameterizedType) type;
051. Type\[] types = type1.getActualTypeArguments();
052. setEntityClass((Class) types\[0]);
053. }
054. getPkname();
055. HQL\_LIST\_ALL="from "+this.entityClass.getSimpleName()+" order by "+pkname+" desc";
056. HQL\_COUNT\_ALL="select count(\*) from "+this.entityClass.getSimpleName();
057. }
058. /\**
059. * 获取主键名称
060. * @return
061. \*/
062. public String getPkname() {
063. Field\[] fields = this.entityClass.getDeclaredFields();//反射类字段
064. for (Field field : fields) {
065. field.isAnnotationPresent(Id.class);
066. this.pkname=field.getName();
067. break;
068. }
069. return pkname;
070. }
071. /\**
072. * 保存实例
073. \*
074. * @param t
075. * @throws HibernateException
076. \*/
077. public void save(T t) throws HibernateException{
078. Session session=null;
079. try {
080. session=sessionFactory.openSession();
081. session.beginTransaction();
082. session.save(t);
083. session.getTransaction().commit();
084. } catch (HibernateException e) {
085. e.printStackTrace();
086. throw new HibernateException(e);
087. }finally{
088. session.close();
089. }
090. }
091. /\**
092. * 修改实例
093. \*
094. * @param t
095. * @throws HibernateException
096. \*/
097. public void update(T t) throws HibernateException{
098. Session session=null;
099. 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&lt;T&gt; findAll() throws Exception {
161. List&lt;T&gt; 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&lt;?&gt; 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&lt;T&gt; findByCriteria(Criteria criteria) throws Exception {
208. List&lt;T&gt; list=null;
209. Session session=null;
210. try {
211. session = sessionFactory.openSession();
212. session.beginTransaction();
213. Criteria criteria1 = session.createCriteria(getEntityClass());
214. criteriacriteria1=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&lt;T&gt; findByExample(T t) throws Exception {
232. List&lt;T&gt; 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&lt;Object\[]&gt; findByHql(String hql,final Object...objects) throws Exception{
258. List&lt;Object\[]&gt; 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 &lt; 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&lt;Object\[]&gt; findBySql(String sql,final Object...objects){
285. List&lt;Object\[]&gt; 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 &lt; 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

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.service;
02. import java.io.Serializable;
03. import java.util.List;
04. import com.sshFrame.zero.dao.BaseDao;
05. /\**
06. * @author 雪精灵
07. \*
08. * @param
09. \*/
10. public class BaseService&lt;T extends Serializable&gt; {
11. protected BaseDao&lt;T&gt; 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&lt;T&gt; findAll() throws Exception{
25. return baseDao.findAll();
26. }
27. public List&lt;T&gt; findByExample(T t) throws Exception{
28. return baseDao.findByExample(t);
29. }
30. public BaseDao&lt;T&gt; getBaseDao() {
31. return baseDao;
32. }
33. public void setBaseDao(BaseDao&lt;T&gt; baseDao) {
34. this.baseDao = baseDao;
35. }
36. }

 

先上7个pojo

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import java.util.HashSet;
04. import java.util.Set;
05. import javax.persistence.CascadeType;
06. import javax.persistence.Column;
07. import javax.persistence.Entity;
08. import javax.persistence.FetchType;
09. 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&lt;Userrole&gt; userroles=new HashSet&lt;Userrole&gt;();
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&lt;Userrole&gt; getUserroles() {
64. return userroles;
65. }
66. public void setUserroles(Set&lt;Userrole&gt; userroles) {
67. this.userroles = userroles;
68. }
69. }

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import java.util.HashSet;
04. import java.util.Set;
05. import javax.persistence.CascadeType;
06. import javax.persistence.Column;
07. import javax.persistence.Entity;
08. import javax.persistence.FetchType;
09. 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&lt;Userrole&gt; userroles=new HashSet&lt;Userrole&gt;();
21. private Set&lt;Rolerights&gt; rolerights=new HashSet&lt;Rolerights&gt;();
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&lt;Userrole&gt; getUserroles() {
41. return userroles;
42. }
43. public void setUserroles(Set&lt;Userrole&gt; userroles) {
44. this.userroles = userroles;
45. }
46. @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="role")
47. public Set&lt;Rolerights&gt; getRolerights() {
48. return rolerights;
49. }
50. public void setRolerights(Set&lt;Rolerights&gt; rolerights) {
51. this.rolerights = rolerights;
52. }
53. }

 

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import java.util.HashSet;
04. import java.util.Set;
05. import javax.persistence.CascadeType;
06. import javax.persistence.Column;
07. import javax.persistence.Entity;
08. import javax.persistence.FetchType;
09. 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&lt;Rolerights&gt; rolerights=new HashSet&lt;Rolerights&gt;();
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&lt;Rolerights&gt; getRolerights() {
40. return rolerights;
41. }
42. public void setRolerights(Set&lt;Rolerights&gt; rolerights) {
43. this.rolerights = rolerights;
44. }
45. }

 

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import java.util.HashSet;
04. import java.util.Set;
05. import javax.persistence.CascadeType;
06. import javax.persistence.Column;
07. import javax.persistence.Entity;
08. import javax.persistence.FetchType;
09. 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&lt;Rightsresources&gt; rightsresourcs=new HashSet&lt;Rightsresources&gt;();
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&lt;Rightsresources&gt; getRightsresourcs() {
48. return rightsresourcs;
49. }
50. public void setRightsresourcs(Set&lt;Rightsresources&gt; rightsresourcs) {
51. this.rightsresourcs = rightsresourcs;
52. }
53. }

 

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import javax.persistence.Column;
04. import javax.persistence.Entity;
05. import javax.persistence.FetchType;
06. import javax.persistence.GeneratedValue;
07. import javax.persistence.Id;
08. import javax.persistence.JoinColumn;
09. 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. }

 

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import javax.persistence.Column;
04. import javax.persistence.Entity;
05. import javax.persistence.FetchType;
06. import javax.persistence.GeneratedValue;
07. import javax.persistence.Id;
08. import javax.persistence.JoinColumn;
09. 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. }

 

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.pojo;
02. import java.io.Serializable;
03. import javax.persistence.Column;
04. import javax.persistence.Entity;
05. import javax.persistence.FetchType;
06. import javax.persistence.GeneratedValue;
07. import javax.persistence.Id;
08. import javax.persistence.JoinColumn;
09. 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. }

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

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.service.users;
02. import java.util.List;
03. import org.springframework.beans.factory.annotation.Autowired;
04. import org.springframework.stereotype.Component;
05. import org.springframework.stereotype.Service;
06. import com.sshFrame.zero.dao.users.UserinfoDao;
07. import com.sshFrame.zero.pojo.Userinfo;
08. import com.sshFrame.zero.service.BaseService;
09. /\**
10. * 用户管理
11. * @author 雪精灵
12. \*
13. * @param
14. \*/
15. @Service
16. @Component("userinfoService")
17. public class UserinfoService extends BaseService&lt;Userinfo&gt;{
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&lt;Userinfo&gt; 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&lt;?&gt; 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&lt;?&gt; 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. }

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.action.users;
02. import java.util.List;
03. import javax.servlet.http.HttpServletRequest;
04. import javax.servlet.http.HttpServletResponse;
05. import org.apache.struts2.convention.annotation.Action;
06. import org.apache.struts2.convention.annotation.Namespace;
07. import org.apache.struts2.convention.annotation.Result;
08. import org.apache.struts2.interceptor.ServletRequestAware;
09. 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&lt;?&gt; 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. }

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.action.users;
02. import javax.servlet.http.HttpServletRequest;
03. import javax.servlet.http.HttpServletResponse;
04. import org.apache.struts2.convention.annotation.Action;
05. import org.apache.struts2.convention.annotation.Namespace;
06. import org.apache.struts2.convention.annotation.ParentPackage;
07. import org.apache.struts2.convention.annotation.Result;
08. import org.apache.struts2.interceptor.ServletRequestAware;
09. 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. }

下面加入拦截器

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.interceptor;
02. import javax.servlet.http.HttpServletRequest;
03. import org.apache.struts2.ServletActionContext;
04. import com.opensymphony.xwork2.Action;
05. import com.opensymphony.xwork2.ActionInvocation;
06. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
07. import com.sshFrame.zero.action.users.UserinfoAction;
08. import com.sshFrame.zero.exception.AhCustomException;
09. 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. }

 

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.interceptor;
02. import javax.servlet.http.HttpServletRequest;
03. import org.apache.log4j.Logger;
04. import org.apache.struts2.ServletActionContext;
05. import org.hibernate.HibernateException;
06. import com.opensymphony.xwork2.Action;
07. import com.opensymphony.xwork2.ActionInvocation;
08. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
09. 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("异常拦截器拦截到异常:"+"&lt;br/&gt;"+"uri为:"+uri+"&lt;br/&gt;"+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("异常拦截器拦截到异常:"+"&lt;br/&gt;"+"action的名称为:"+uri+"&lt;br/&gt;"+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("异常拦截器拦截到异常:"+"&lt;br/&gt;"+"action的名称为:"+uri+"&lt;br/&gt;"+e);
41. eexcMessage=e.getExcMessage();
42. request.setAttribute("msg", excMessage);
43. result=Action.ERROR;
44. }catch (Exception e) {
45. e.printStackTrace();
46. logger.error("异常拦截器拦截到异常:"+"&lt;br/&gt;"+"action的名称为:"+uri+"&lt;br/&gt;"+e);
47. excMessage=AhCustomException.getExcMessage(ExcCode.AppError);
48. request.setAttribute("msg", excMessage);
49. result=Action.ERROR;
50. }
51. return result;
52. }
53. }

自定义异常类

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

01. package com.sshFrame.zero.exception;
02. /\**
03. * 自定义异常处理
04. * @author 雪精灵
05. \*/
06. public class AhCustomException extends Exception{
07. private static final long serialVersionUID = 1L;
08. /\**
09. * 错误类型标识
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. "您可能还没有登录本系统，或者已经超时，您必须先登录本系统后才能使用该功能&lt;p&gt;&lt;a href='../' target='\_parent'&gt;重新登录&lt;/a&gt;&lt;/p&gt;"
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. excCodeexcCode = excCode.AppError;
81. }
82. }

下面加入页面，index.jsp,在webContent下

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

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

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

Html代码  [![收藏代码](http://happysnowcity.iteye.com/images/icon_star.png)](http://happysnowcity.iteye.com/blog/1770872 "收藏这段代码")

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

程序下载链接：[http://download.csdn.net/detail/doublelucklysnow/5001504](http://download.csdn.net/detail/doublelucklysnow/5001504)

转自：[http://www.cnblogs.com/aocle/archive/2013/06/11/3132038.html](http://www.cnblogs.com/aocle/archive/2013/06/11/3132038.html)