whp0731 发表于 2013-2-7 16:03:22

Struts2学习之十五-声明式的异常处理

看下文前可以先参考:
http://blog.chinaunix.net/u2/84280/showart_1728277.html 
 
 
 

package com.test.exception;public class UsernameException extends Exception{ private String message;public UsernameException(String message) {super(message);    this.message = message; } public String getMessage() {return message; } public void setMessage(String message) {this.message = message; }} 声明式的异常处理

1、类

 
 
package com.test.exception;public class PasswordException extends Exception{ private String message; public PasswordException(String message) {super(message);this.message = message; } public String getMessage() {return message; } public void setMessage(String message) {this.message = message; }} 
 
2、action类修
public String execute() throws Exception {//username invalidif(!"hello".equals(this.getUsername())){   throw new UsernameException("username invalid");}//password invalidelse if(!"world".equals(this.getPassword())){   throw new PasswordException("password invalid");}else{   return SUCCESS;}} 
3、修改struts.xml
全局配置方式:
  
<global-results>   <result name="passwordInvalid">/passwordInvalid.jsp</result></global-results>      <global-exception-mappings>   <exception-mapping result="passwordInvalid" exception="com.test.exception.PasswordException"></exception-mapping></global-exception-mappings>局部配置方法:<action name="login" class="com.test.action.LoginAction">   <exception-mapping result="usernameInvalid" exception="com.test.exception.UsernameException"></exception-mapping>      <result name="success">/result.jsp</result>   <result name="usernameInvalid">/usernameInvalid.jsp</result></action> 
4、新增jsp页面
1)usernameInvalid.jsp(举例用EL表达式)
<%@ page language="java" contentType="text/html; charset=GB18030"    pageEncoding="GB18030"%>    <%@ taglib prefix="s" uri="/struts-tags" %>    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>Insert title here</title></head><body>${exception.message }</body></html> 
2)passwordInvalid(也可以打印堆栈信息)
<%@ page language="java" contentType="text/html; charset=GB18030"    pageEncoding="GB18030"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>Insert title here</title></head><body><s:property value="exceptionStack"/></body></html> 
 
 
 
页: [1]
查看完整版本: Struts2学习之十五-声明式的异常处理