1.处理方式
一般是把异常往外抛,然后再struts.xml文件中配置相应的全局异常。
1.在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 c = null;
while(rs.next()) {
c = new Category();
c.setId(rs.getInt("id"));
c.setName(rs.getString("name"));
c.setDescription(rs.getString("description"));
categories.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
//捕获异常
throw(e);
}
DB.close(ps);
DB.close(conn);
return categories;
}
2.在action中将异常并抛出。
public String list() throws SQLException {
categories = categoryService.list();
return SUCCESS;
}
3.在sturt.xml文件中配置。
action层中的package配置要继承这包。
<package name="bbs2009exception" extends="struts-default">
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error" exception="java.sql.SQLException"></exception-mapping>
</global-exception-mappings>
</package>
2.struts2异常处理过程
当页面访问action中的方法发现异常时,会去配置action的package中找,有没有对应的异常exception-mapping的配置,没有则会去继承的包中找。有,发现返回的结果是error,然后发现有个全局结果集叫error,访问其中的页面。