[Spring] 18. springMVC supports Exception Handling. springspringmvc

Source: Internet
Author: User

[Spring] 18. springMVC supports Exception Handling. springspringmvc

No matter what the project is, exception handling is very necessary, and you can't throw some error code that only programmers can understand to the user, so at this time, a unified exception handling is performed, it is necessary to display a friendly error page. Like other MVC frameworks, springMVC also has its own exception handling mechanism.
SpringMVC provides two main methods for exception handling. One is to directly implement HandlerExceptionResolver. Of course, this also includes SimpleMappingExceptionResolver and DefaultHandlerExceptionResolver, the other is to use annotations to implement a Controller -- ExceptionHandler dedicated to exception handling.

 

 

1. Implement your own HandlerExceptionResolver and HandlerExceptionResolver is an interface. springMVC itself has its own implementation-DefaultHandlerExceptionResolver, the parser only blocks some of the typical exceptions and returns the corresponding error code. Of course, you can inherit the DefaultHandlerExceptionResolver class, then, rewrite some of the exception handling methods to implement your own exception handling.

import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;    import org.springframework.web.servlet.HandlerExceptionResolver;  import org.springframework.web.servlet.ModelAndView;    public class ExceptionHandler implements HandlerExceptionResolver {        @Override      public ModelAndView resolveException(HttpServletRequest request,              HttpServletResponse response, Object handler, Exception ex) {          // TODO Auto-generated method stub          return new ModelAndView("exception");      }    }  

 

 

The above 4th resolveException parameters indicate the types of exceptions to be processed. Because the Exception class is the base class of all Exception classes, if you want to perform different processing based on the Exception type, in the resolveException method, you can perform different processing based on different exception types and return different exception views. For example:

public class ExceptionHandler implements HandlerExceptionResolver {        @Override      public ModelAndView resolveException(HttpServletRequest request,              HttpServletResponse response, Object handler, Exception ex) {          // TODO Auto-generated method stub          if (ex instanceof NumberFormatException) {              //doSomething...              return new ModelAndView("number");          } else if (ex instanceof NullPointerException) {              //doSomething...              return new ModelAndView("null");          }          return new ModelAndView("exception");      }    }  

 

After such an exception processor is defined, such a bean object must be defined in applicationContext, for example:

<Bean id = "exceptionResolver" class = "com. tiantian. xxx. web. handler. ExceptionHandler"/>

In addition to implementing a handler, Spring also implements SimpleMappingExceptionResolver, both of which are inherited from the abstract class AbstractHandlerExceptionResolver, while AbstractHandlerExceptionResolver implements the resolveException method of the HandlerExceptionResolver interface, two abstract methods are extracted. One is the prepareResponse (exception, response) method executed before exception handling, and the other is the doResolveException (request, response, handler, exception) method. SimpleMappingExceptionResolver, as its name implies, is to determine which view to handle the current error information through a simple ing relationship. SimpleMappingExceptionResolver provides ing between exceptions and views through exception-type exceptionings ings, and ing the view name returned by exceptions and the return code of the corresponding HttpServletResponse through statusCodes in case of exceptions. You can also use defaultErrorView and defaultErrorCode to specify the default value. defaultErrorView indicates that the view defined by defaultErrorView is returned if the corresponding exception type is not found in predictionmappings, defaultErrorCode indicates the return code returned by default when the stating between the view and return code is not found in statusCodes. When SimpleMappingExceptionResolver is used, when an exception occurs, SimpleMappingExceptionResolver puts the current exception object in its own attribute predictionattribute. If exceptionAttribute is not specified, exceptionAttribute is the default exception.

 

The following is a simple example:

 

(1) declare a SimpleMappingExceptionResolver bean in the servlet configuration file of SpringMVC, and specify the ing between exceptions and views by configuring the exceptionMappings and defaultExceptionView attributes.

Xml Code
<Bean class = "org. springframework. web. servlet. handler. simpleMappingExceptionResolver "> <property name =" exceptionMappings "> <props> <prop key =" NumberFormatException "> number </prop> <! -- Returns the view named number when NumberFormatException is thrown --> <prop key = "NullPointerException"> null </prop> </props> </property> <property name = "defaultErrorView" value = "exception"/> <! -- Indicates that when an exception is thrown but the corresponding exception is not found in exceptionMappings, the view named exception is returned --> <property name = "statusCodes"> <! -- Define the relationship between the view and return code when an exception occurs --> <props> <prop key = "number"> 500 </prop> <! -- Indicates that the view number is returned when NumberFormatException occurs, the return code of HttpServletResponse corresponding to the graph number in case of an exception is defined as 500 --> <prop key = "null"> 503 </prop> </props> </property> <property name = "defaultStatusCode" value = "404"/> <! -- Indicates the default return code of HttpServletResponse when an exception occurs. The default value is 200. --> </bean>

(2) access as follows:

@ Controller @ RequestMapping ("/test") public class TestController {@ RequestMapping ("/null") public void testNullPointerException () {Blog blog = null; // a null pointer exception occurs here, and then a null view System defined in the SpringMVC configuration file is returned. out. println (blog. getId ();} @ RequestMapping ("/number") public void testNumberFormatException () {// NumberFormatException occurs here, then, the number view Integer defined in the SpringMVC configuration file is returned. parseInt ("abc");} @ RequestMa Pping ("/default") public void testDefaultException () {if (1 = 1) // The exception type is not specified in the SpringMVC configuration file, therefore, the default exception view throw new RuntimeException ("Error! ");}}

 

 

(3) exception objects that can be accessed on the Jsp page. Here, the return view number. jsp of NumberFormatException is used as an example:

Jsp code
<% @ Page language = "java" import = "java. util. * "pageEncoding =" GB18030 "isErrorPage =" true "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

 

2. Use @ ExceptionHandler for processing

 

One bad thing about using @ ExceptionHandler for processing is that the exception handling method must be in the same Controller as the error method.

 

For example:

Java code
Import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. exceptionHandler; import org. springframework. web. bind. annotation. requestMapping; import com. tiantian. blog. web. servlet. myException; @ Controller public class GlobalController {/*** used to handle exceptions * @ return */@ ExceptionHandler ({MyException. class}) public String exception (MyException e) {System. out. println (e. g EtMessage (); e. printStackTrace (); return "exception" ;}@ RequestMapping ("test") public void test () {throw new MyException ("error! ");}}

 

When you access the test method on the page, an error is reported. The Controller that owns the test method has another method to handle the exception. At this time, the method to handle the exception is called.

 

 

Priority

Since SpringMVC has two exception handling methods, there is a priority problem:

 

When an exception occurs, SpringMVC will handle the following:

(1) SpringMVC will first find the exception parser HandlerExceptionResolver from the configuration file

(2) If the exception parser is found, the next step is to determine whether the parser can handle the current exception.

(3) if it can be processed, it will be processed and the corresponding exception view will be returned to the foreground.

(4) If the corresponding exception parser is not found or the found exception parser cannot handle the current exception, check whether the corresponding exception processor is provided in the current Controller, if the service is provided, the Controller processes the service and returns the corresponding view.

(5) If the corresponding exception parser is not defined in the configuration file and is not defined in the current Controller, the exception will be thrown out.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.