【Struts2框架】第五节声明式异常处理-处理异常的过程

如何抓到异常的?
步骤:(以之前写的小样例为例)

如果CategoryService中的list方法出错(category_表不存在):
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;
	}
做到两点:throws SQLException和throw(e);

此时CategoryAction接收到CategoryService中的list方法抛出的异常:
public String list()throws Exception{
		categories=categoryService.list();
		return SUCCESS;
	}
注意加:throws Exception

CategoryAction中的throws Exception继续向外抛异常,之后struts.xml接住
<action name="*-*" class="cn.hpu.bbs.action.{1}Action" method="{2}">
       	    <result>/admin/{1}-{2}.jsp</result>
            <result name="input">/admin/{1}-{2}.jsp</result>    
            <result name="update">/admin/{1}-{2}.jsp</result>   
            <exception-mapping result="error" exception="java.sql.SQLException"/>  
            <result name="error">/error.jsp</result>
 </action>

其中 <exception-mapping result="error" exception="java.sql.SQLException"/>  
java.sql.SQLException异常有对应的result,找到result(error.jsp),显示异常的界面

在error.jsp中利用[Debug]可以看到,栈值中有exception,详细为:
exception   java.sql.SQLException: Table 'bbs2014.category_' doesn't exist

友好界面里最好写“出错了,请联系管理员”,要比“请稍后再试”好多了

全局的异常处理:
如果需要收集的异常过多,那么需要全局的异常处理机制,在struts中这样配置:
<package name="bbs2014_default" extends="struts-default">
	<global-results>
		<result name="error">/error.jsp</result>
	</global-results>
	
	<global-exception-mappings>
    		<exception-mapping result="error" exception="java.sql.SQLException"/>
    	</global-exception-mappings>
</package>
<!--extends="bbs2014_default"继承上面那个公用package-->
<package name="admin" namespace="/admin" extends="bbs2014_default">
       <action name="*-*" class="cn.hpu.bbs.action.{1}Action" method="{2}" >
       		<result>/admin/{1}-{2}.jsp</result>
            <result name="input">/admin/{1}-{2}.jsp</result>    
            <result name="update">/admin/{1}-{2}.jsp</result>   
</action>
struts中支持声明式的异常处理指的是,要是有异常,就向外抛,最后会给一个统一的接口,然后让你在特定的页面做出处理。


转载请注明出处:http://blog.csdn.net/acmman/article/details/47086261

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值