javaEE Struts2,配置全局异常处理,jsp中通过OGNL表达式标签获取异常信息

 

UserAction.java(Action抛出异常):

package cn.xxx.web.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.xxx.domain.User;
import cn.xxx.service.UserService;
import cn.xxx.service.impl.UserServiceImpl;

public class UserAction extends ActionSupport implements ModelDriven<User> {
	private User user = new User();
	private UserService us  = new UserServiceImpl();
	
	public String login() throws Exception { // 抛出异常。通过Struts.xml配置文件处理异常
		if(XXX){
			throw new RuntimeException("异常信息!");
		}

		return "toHome";
	}

	@Override
	public User getModel() {
		return user;
	}

}

src/struts.xml(Struts2配置文件;配置全局异常处理):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<!-- 指定struts2是否以开发模式运行
			1.热加载主配置.(不需要重启即可生效)
			2.提供更多错误信息输出,方便开发时的调试
	 -->
	<constant name="struts.devMode" value="true"></constant>
	<package name="crm" namespace="/" extends="struts-default" >
		<global-exception-mappings>
			<!-- 如果出现java.lang.RuntimeException异常,就将跳转到名为"error"的结果 -->
			<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
		</global-exception-mappings>
		
		<action name="UserAction_*" class="cn.xxx.web.action.UserAction" method="{1}" >
			<result name="toHome" type="redirect" >/index.htm</result>
			<result name="error"  >/login.jsp</result>  <!-- 如果发生RuntimeException异常,跳到该结果中 -->
		</action>
	</package>
</struts>

login.jsp(通过OGNL表达式标签获取异常信息):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>   <!-- 导入标签库 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/frameset.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<META http-equiv=Content-Type content="text/html; charset=utf-8">

</HEAD>
	<BODY>
		<FORM id=form1 name=form1 action="${pageContext.request.contextPath}/UserAction_login"  method=post>
			<!-- .................. -->
			<s:property value="exception.message" />   <!-- 通过OGNL表达式获取异常信息 -->
			<input type="submit" value="提交" />
		</FORM>
		
		<s:debug></s:debug>  <!-- 调试,查看ValueStack(OGNLContext)中的内容 -->
	</BODY>
</HTML>

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值