六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 31|回复: 0

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

[复制链接]

升级  36.67%

25

主题

25

主题

25

主题

秀才

Rank: 2

积分
105
 楼主| 发表于 2013-2-7 16:03:22 | 显示全部楼层 |阅读模式
看下文前可以先参考:
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 invalid  if(!"hello".equals(this.getUsername()))  {   throw new UsernameException("username invalid");  }  //password invalid  else 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> 
 
 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表