springmvc自定义异常信息

package com.itheima.exception;

public class CustomException extends Exception {

	// 定义异常的消息
	private String message;

	public CustomException(String message) {
		this.message = message;
	}

	// 获取异常信息
	public String getMessage() {
		return message;
	}
}

CustomException自定义异常类,通过有参构造函数保存错误信息

 

package com.itheima.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 自定义异常处理器
 * @author ChonZ
 *
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		//打印异常信息
		ex.printStackTrace();
		
		//定义一个自己的异常类对象
		CustomException customException = null;
		
		//判断当前传入的异常对象是否是自定义异常对象
		if(ex instanceof CustomException) {
			customException = (CustomException)ex;
		} else {
			customException = new CustomException("系统问题,请联系管理员");
		}
		
		//创建ModelAndView对象
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		mv.addObject("errorMessage", customException.getMessage());
		return mv;
	}
}

CustomExceptionResolver自定义异常信息处理器,通过重写的方法,判断异常是否为自定义异常,是就直接使用异常信息,不是就按照指定的统一异常信息,通过ModelAndView绑定错误信息到目标页面去.

 

package com.itheima.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.itheima.exception.CustomException;

/**
 * springmvc的异常处理
 * @author ChonZ
 *
 */
@Controller("exceptionController")
@RequestMapping("/springmvc")
public class ExceptionController {
	
	/**
	 * 测试自定义异常处理
	 * @param username
	 * @return
	 * @throws CustomException 
	 */
	@RequestMapping("/testException")
	public String testException(String username) throws CustomException {
		System.out.println("testException方法执行了..." + username);
		//判断用户名是否为空,如果为空的话,抛出异常
		if(StringUtils.isEmpty(username)) {
			throw new CustomException("用户名为空");
		}
		return "success";
	}	
}

ExceptionController 错误信息Controller类,用于模拟异常产生

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd">
		<!-- 告知spring创建容器时要扫描的包 -->
		<context:component-scan base-package="com.itheima"></context:component-scan>
		
		<!-- 配置springmvc的视图解析器,用于找到响应的jsp -->
		<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/WEB-INF/pages/"></property>
			<property name="suffix" value=".jsp"></property>
		</bean>
		
		<!-- 配置自定义异常处理器 -->
		<bean id="handlerExceptionResolver" class="com.itheima.exception.CustomExceptionResolver"/>
		
		<!-- 开启springmvc的注解  -->
		<mvc:annotation-driven></mvc:annotation-driven>
		
		<!-- 设置静态资源不参与springmvc编码的过滤 -->
		<mvc:resources location="/css/" mapping="/css/**"/>
		<mvc:resources location="/images/" mapping="/images/**"/>
		<mvc:resources location="/scripts/" mapping="/javascripts/**"/>
</beans>

pringmvc.xml配置文件

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>day02_springmvc5_01response</display-name>


	<!-- 配置springmvc核心控制器 -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

		<!-- 加载springmvc配置文件 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<!-- 请求过滤器,把请求交给springmvc处理 -->
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 配置springmvc提供的编码过滤器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>




	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

web.xml配置文件

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>springmvc的异常处理</title>
</head>
<body>
	<!-- 原始方式文件上传的表单 -->
	<form action="springmvc/testException" method="post">
		用户名称:<input type="text" name="userName"/><br/>
		<input type="submit" value="保存">
	</form>
	
</body>
</html>

index.jsp测试页面

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>错误提示页面</title>
</head>
<body>
执行失败:${errorMessage}
</body>
</html>

error.jsp错误信息显示页面

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>成功页面</title>
</head>
<body>
执行成功
</body>
</html>

成功页面

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring MVC中,可以通过实现HandlerExceptionResolver接口来进行自定义异常处理。这个接口定义了一个resolveException()方法,当请求处理过程中出现异常时会被调用。通过实现这个方法,我们可以自定义异常处理的逻辑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springmvc自定义异常处理](https://blog.csdn.net/Sunking_Yin/article/details/52744151)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringMVC自定义异常处理](https://blog.csdn.net/A_jungle/article/details/82386793)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [ssm_异常处理](https://download.csdn.net/download/csdn_kenneth/10251825)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值