struts 异常处理 (全局异常处理)

本文介绍如何在Struts框架中实现全局异常处理,包括自定义异常类、在代码中抛出异常、配置struts.xml文件以实现异常到特定页面的跳转等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录一下全局异常处理的过程;处理主动抛出的异常,转向错误提示页面。

      1、写一个自己的异常,继承runtimeexception,从父类生成构造方法;

package me.yndy.srtp.exception;

@SuppressWarnings("serial")
public class ErrorException extends RuntimeException {

	public ErrorException() {
		super();
	}

	public ErrorException(String message, Throwable cause) {
		super(message, cause);
	}

	public ErrorException(String message) {
		super(message);
	}

	public ErrorException(Throwable cause) {
		super(cause);
	}


}

2.代码中需要手动抛出异常

if(content==null||"".equals(content.trim())) {
			throw new ErrorException("内容不能为空!");//手动抛出异常
		}
3.在struts.xml文件中敌营全局异常,异常跳转界面为error.jsp

<struts>
	<!-- 设置扩展名 -->
	<constant name="struts.action.extension" value="action,do" />
	<!-- 设置修改了配置文件不用重新启动 -->
	<constant name="struts.configuration.xml.reload" value="true" />
	
	<package name="default" namespace="/" extends="struts-default">
		<!--配置全集结果集 , -->
		<global-results>
			<result name="error">/error.jsp</result>
		</global-results>
		<!-- 异常处理 -->
		<global-exception-mappings>
			<exception-mapping result="error"
			 exception="me.yndy.srtp.exception.ErrorException">
			</exception-mapping>
		</global-exception-mappings>
		<!-- 通配符匹配action -->
		<action name="*_*" class="me.yndy.srtp.controller.{1}Action"
			method="{2}">
			<result name="success">/{1}/{2}.jsp</result>
			<result name="input">/{1}/{2}Input.jsp</result>
			<result name="redirect" type="redirect">/${#urlAction}</result>
		</action>

	</package>
</struts>

4、error.jsp

<div class="content">
   <!--  以后加上bootstrap的大屏幕,增加界面的统一性-->
    	<p>${exception.message}</p>
    	<!--返回上一页,此种用法不会丢失上一页的内容  -->
    	<p><a href="javascript:history.go(-1);">点此返回</a></p>
    	 
   </div>
总结:这样就配置了全局异常处理,可以对所有的action生效,可以配置局部异常处理,在struts.xml中的action内,配置,可以针对单个action生效。如果在某个action中配置了局部异常处理,一个异常同时对应了局部异常和全局异常,那么会执行局部异常处理的代码,局部异常处理的优先级高,会将全局的覆盖了。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值