使用@ExceptionHandler的Spring-MVC异常处理示例

时间:2020-02-23 14:35:54  来源:igfitidea点击:

在本教程中,我们将看到如何使用@ExceptionalHandler在SpringMVC中进行异常处理。当异常发生时,可以使用@ExceptionHandler重定向到错误视图。
让我们通过例子来理解这一点:

步骤

1)使用Maven在Eclipse中创建动态Web项目名为"SpringmvcexceptionalHaremple"

Maven依赖项

2)我们的pom.xml看起来如下

pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.igi.theitroad</groupId>
  <artifactId>SpringRestfulWebServicesWithJSONExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>
 
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <dependency>
            <groupId>com.fasterxml.Hymanson.core</groupId>
            <artifactId>Hymanson-databind</artifactId>
             <version>2.4.1</version>
        </dependency>
 </dependencies>
 <build>
  <finalName>SpringRestfulWebServicesWithJSONExample</finalName>
 
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 
 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring应用程序配置:

3)更改Web.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_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
 
  </welcome-file-list>
 <servlet>
 <servlet-name>springrest</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
 <servlet-name>springrest</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>
 
</web-app>

4)在/Web-Inf /文件夹中创建名为springrest-servlet.xml的XML文件。
请更改上下文:组件扫描如果要使用不同的套装来搜索控制器。
请参阅Spring MVC Hello World示例以获取更多的理解。

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
 <mvc:annotation-driven
<context:component-scan base-package="org.igi.theitroad.controller" 
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 <mvc:default-servlet-handler
</beans>

创建控制器

6)在包org.igi.theitroad.Controller中创建名为"helloWorldcontroller.java"的控制器

package org.igi.theitroad.controller;
 
import java.io.IOException;
 
import org.apache.log4j.Logger;
import org.igi.theitroad.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class HelloWorldController {
 
	private static final Logger logger = Logger
			.getLogger(HelloWorldController.class);
 
	@RequestMapping("/helloworld/{helloType}")
	public ModelAndView hello(@PathVariable("helloType") String helloType)
			throws CustomException, IOException {
 
		String helloWorldMessage="";
		if (helloType.equalsIgnoreCase("CustomException")) {
			throw new CustomException("Custom exception occured");
		} else if (helloType.equalsIgnoreCase("IOException")) {
			throw new IOException(" IO exception occured");
		} else {
			helloWorldMessage = "Hello world from theitroad!";
			
		}
 
		return new ModelAndView("hello", "message", helloWorldMessage);
	}
 
	@ExceptionHandler(CustomException.class)
	public ModelAndView catchCustomException(CustomException ex) {
 
		ModelAndView model = new ModelAndView("Custom_Exception");
		model.addObject("errorMessage", ex.getMessage());
		return model;
	}
	
	@ExceptionHandler(IOException.class)
	public ModelAndView catchIOException(IOException ex) {
 
		ModelAndView model = new ModelAndView("IOException");
		model.addObject("errorMessage", ex.getMessage());
		return model;
	}
}

创建视图

正如我们所看到的,我们已经注释了两种方法:CatchCustomexception和@ExceptionHandler的CatchioException。
这些方法分别处理CoreMexception和IoException。

修改下面的index.jsp a s

<%@ 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>HelloWorld</title>
</head>
<body>
Hello World!!
</body>
</html>

在/web-inf /文件夹中创建custom_excepion.jsp以处理cortomexception异常。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Custom Exception</title>
</head>
<body>
${errorMessage}
</body>
</html>

在下面创建IoException.jsp中/web-inf文件夹中以处理ioException。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>IO Exception</title>
</head>
<body>
${errorMessage}
</body>
</html>

7)这是时候做Maven建造了。

右键单击项目 - >运行AS - > Maven Build

8)将目标作为清洁安装(下面给出),然后单击运行

运行应用程序

9)右键单击项目 - >在服务器上运行AS - >运行

选择Apache Tomcat,然后单击"完成"

10)让我们下面点击URL http://localhost:8080/springmvcexceptionalhlerexample/helloworld/hello

正如我们所看到的,它与UP上的URL正常工作。
现在让我们击中一些URL,它将抛出异常,并且例外将由@ExcpetionHandler处理。

当你下面点击你的网址。
http://localhost:8080/springmvcexceptionalhlerexample/helloworld/coreomexception

如我们所见,当我们按下URL时,通过CARTCustomexception方法抛出并处理CoreMexception。

当你下面点击你的网址。
http://localhost:8080/springmvcexceptionallerexample/helloworld/ioException

正如我们所看到的,当我们按下URL时,通过CatchioException方法抛出并处理CoreMexception。