Service 往外抛异常
public List<Category> list() throws SQLException{
Connection conn = DB.createConn();
String sql = "select * from _category_";
PreparedStatement ps = DB.prepare(conn, sql);
List<Category> categories = new ArrayList<Category>();
try {
ResultSet rs = ps.executeQuery();
Category category = null;
while(rs.next()){
category = new Category();
category.setId(rs.getInt("id"));
category.setName(rs.getString("name"));;
category.setDescription(rs.getString("description"));
categories.add(category);
}
DB.close(rs);
} catch (SQLException e) {
e.printStackTrace();
throw(e);
}
DB.close(ps);
DB.close(conn);
return categories;
}
Action 层 接着往外抛,交给Struts2 进行处理:
public String list() throws Exception {
categories = categoryService.list();
return SUCCESS;
}
在 struts.xml 中的配置:
<package name="bbs2009_default" extends="struts-default">
<global-results>
<result name="error">/error.jsp</result>
</global-results> <global-exception-mappings>
<exception-mapping result="error" exception="Exception"/>
</global-exception-mappings>
</package>
然后其他的 package 继承 bbs2009_default 就行了,以后出了方法中catch的异常(比如上面的SQLException),就会跳转到/error.jsp,web app 界面更加友好一些。package的继承结构如下图:
测试:
链接: http://pan.baidu.com/s/1c1Xzvw8 密码: 9nh2