标签:des style blog io ar color os 使用 sp
一,声明式异常处理:
第一步:首先在有可能抛出异常的方法里面throws exception
public List<Category> list() throws SQLException { Connection conn = DB.createConn(); String sql = "select * from _category_"; //数据库里面没有这个table,产生异常 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; }
第二步:.在Actoin中进行异常映射
public String list() throws Exception { categories = categoryService.list(); return SUCCESS; }
第三步:在package中进行异常映射
1.方法一:定义action自己的异常
<struts> <constant name="struts.devMode" value="true"></constant> <package name="admin" namespace="/admin" extends="struts-default" > <action name="index"> <result>/admin/index.html</result> </action> <action name="*-*" class="com.bjsxt.bbs2009.action.{1}Action" method="{2}"> <result>/admin/{1}-{2}.jsp</result> <result name="input">/admin/{1}-{2}.jsp</result> <exception-mapping result="error" exception="java.sql.SQLException" /> //发生java.sql.SQLException异常时会跳转到error.jsp <result name="error">/error.jsp</result> </action> </package> </struts>
2.方法二:使用继承共用异常映射(把所有的异常都交给global-results 处理)
<struts> <constant name="struts.devMode" value="true"></constant> <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="java.lang.Exception"></exception-mapping> </global-exception-mappings> </package> <package name="admin" namespace="/admin" extends="bbs2009_default" > <action name="index"> <result>/admin/index.html</result> </action> <action name="*-*" class="com.bjsxt.bbs2009.action.{1}Action" method="{2}"> <result>/admin/{1}-{2}.jsp</result> <result name="input">/admin/{1}-{2}.jsp</result> <!-- <exception-mapping result="error" exception="java.sql.SQLException" /> <result name="error">/error.jsp</result> --> </action> </package> </struts>
二,Struts2中异常处理由拦截器实现(观察struts-default.xml)
a) 实际上Struts2的大多数功能都由拦截器实现
标签:des style blog io ar color os 使用 sp
原文地址:http://www.cnblogs.com/enjoy-life-clh/p/4102612.html