Struts2---声明式异常处理

在service方法里 throw抛出一个异常, 然后再方法声明上加上throws:

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;
	}

在调用list方法的action里 throws, 这样就不用try catch而是由struts2处理:

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

struts.xml里如何配置?

 <package name="admin" namespace="/admin" extends="struts-default" >
    <default-action-ref name="index"/>
   		<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>
<result name="exception_handle">/admin/exception.jsp</result> </action> </package>

service里的sql语句改成错误的, 这样在调用页面的时候, 就会显示error.jsp.

下面是异常处理最常用的方法:

1. 配置新的package, global results, global-exception-mappings, 自己的action的包继承异常包即可.

原理:::拦截器 

<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"></exception-mapping>
    	</global-exception-mappings>
	</package>
	
    <package name="admin" namespace="/admin" extends="bbs2009_default" >
    <default-action-ref name="index"/>
   		<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>-->
       		<result name="exception_handle">/admin/exception.jsp</result>
       </action>
    </package>

  

  

原文地址:https://www.cnblogs.com/wujixing/p/5394125.html