Strut2_声明式异常处理

Service 往外抛异常

 1     public List<Category> list() throws SQLException{
 2         Connection conn = DB.createConn();
 3         String sql = "select * from _category_";
 4         PreparedStatement ps = DB.prepare(conn, sql);
 5         List<Category> categories = new ArrayList<Category>();
 6         try {
 7             ResultSet rs = ps.executeQuery();
 8             Category category = null;
 9             while(rs.next()){
10                 category = new Category();
11                 category.setId(rs.getInt("id"));
12                 category.setName(rs.getString("name"));;
13                 category.setDescription(rs.getString("description"));
14                 categories.add(category);
15             }
16             DB.close(rs);
17         } catch (SQLException e) {
18             e.printStackTrace();
19             throw(e);
20         }
21         DB.close(ps);
22         DB.close(conn);
23         return categories;
24     }

Action 层 接着往外抛,交给Struts2 进行处理:

1     public String list() throws Exception {
2         categories = categoryService.list();
3         return SUCCESS;
4     }

在 struts.xml 中的配置:

1     <package name="bbs2009_default" extends="struts-default">
2         <global-results>
3             <result name="error">/error.jsp</result>
4         </global-results>
5     
6          <global-exception-mappings>
7             <exception-mapping result="error" exception="Exception"/>
8         </global-exception-mappings>
9     </package>

然后其他的 package 继承 bbs2009_default 就行了,以后出了方法中catch的异常(比如上面的SQLException),就会跳转到/error.jsp,web app 界面更加友好一些。package的继承结构如下图:

测试:

链接: http://pan.baidu.com/s/1c1Xzvw8 密码: 9nh2

原文地址:https://www.cnblogs.com/ShawnYang/p/6680899.html