1. 声明式异常
//struts.xml
<struts>
<constant name="struts.devMode" value="true"></constant>
<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 name="admin" namespace="/admin" extends="struts-default" >
<action name="userList" class="UserAction" method="list">
<result>/userAdd.jsp</result>
<!-- <exception-mapping result="error" exception="java.sql.SQLException" />
<result name="error">/error.jsp</result> -->
</action>
</package>
</struts>
//CategoryAction
public class CategoryAction extends ActionSupport {
private User user;
//Action接到user.list()抛来的异常,并把它抛出struts2,struts2根据struts.xml里的配置找到相应页面
public String list() throws Exception {
categories = user.list();
return SUCCESS;
}
}
//UserService
public class UserService {
public List<User> list() throws SQLException {
Connection conn = DB.createConn();
String sql = "select * from t_user_"; //故意写错,产生java.sql.Exception,抛给了UserAction
PreparedStatement ps = DB.prepare(conn, sql);
List<User> users= new ArrayList<User>();
try {
ResultSet rs = ps.executeQuery();
User u= null;
while(rs.next()) {
u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
users.add(u);
}
} catch (SQLException e) {
e.printStackTrace();
throw(e);
}
DB.close(ps);
DB.close(conn);
return categories;
}
}