Springmvc Exception Handling

Source: Internet
Author: User

We know that the exception in the system includes: compile-time exception and run-time exception runtimeexception, the former by catching the exception to obtain the exception information, the latter mainly through the specification code development, test through means to reduce the occurrence of runtime exceptions. In the development, whether the DAO layer, service layer or controller layer, it is possible to throw an exception, in Springmvc, all types of exception processing can be decoupled from the processing process, not only to ensure that the relevant processing process of a single function, It also realizes the unified processing and maintenance of abnormal information.

①1. Spring comes with exception handler

Spring comes with an exception handler Simplemappingexceptionresolver, which implements the Handlerexceptionresolver, Use Simplemappingexceptionresolver to configure the following nodes in Spring.xml

<!--parameter Method name Resolver--   <bean id= "Methodnameresolver" class= " Org.springframework.web.servlet.view.InternalResourceViewResolver ">       <property name=" prefix "value="/ day10exception/"/>       <property name=" suffix "value=". jsp "/>   </bean>    <!-- All of the labeled classes under the scan package--    <context:component-scan base-package= "cn.happy.day10Exception"/><!--Exception processor--    <bean class= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >        <!-- Default error View--        <property name= "Defaulterrorview" value= "error"/>        <!--exception type--        <property Name= "Exceptionattribute" value= "ex"/>    </bean>

2. Customizing an exception

Custom exception public class Usernameexception extends Exception {    //Override construct public    usernameexception () {        super ();    } Public    usernameexception (String message) {        super (message);}    }

  

3. Test procedures

Import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.requestmapping;@ Controllerpublic class Firstcontroller {    @RequestMapping ("/first") public    String Dofirst (String username,int Age) throws Exception {        //If user name does not equal admin error if        (!username.equals ("admin")) {            throw new Usernameexception ("User name error");        }        Jump to Dosecond page        return "Dosecond";    }}

Then we enter the URL in the foreground to test the http://localhost:8080/first?username=admin1, deliberately passing a wrong value, the program will go to the default Error view page.

② Exception Processor Boost version

You need to add a Exceptionmappings property to the Simplemappingexceptionresolver node, which is the properties type

<!--exception Processor--    <bean class= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >        <!--default error view-        <property name= "Defaulterrorview" value= "error"/>        <!--exception Type--        <property name= "Exceptionattribute" value= "ex"/>        <property name= "Exceptionmappings" >            <props>                <!--key: Exception type   val: page to go when an exception occurs--                <prop key= "Usernameexception" >name</ prop>                <prop key= "ageexception" >age</prop>            </props>        </property>    </bean>

The key value represents the custom exception type, and value represents the JSP page that was turned when the current exception occurred

③ Custom Exception handlers

Custom exception type processor needs to implement Handlerexceptionresolver interface

Custom Exception processor public class Myhandlerexceptionresolver implements Handlerexceptionresolver {    /**     *     * @param HttpServletRequest  Request     * @param httpservletresponse   response     * @param o object     * @param e     Returns the exception type     * @return *     /public    Modelandview resolveexception (HttpServletRequest httpservletrequest, HttpServletResponse HttpServletResponse, Object o, Exception e) {        //CREATE VIEW model object        Modelandview mv=new Modelandview ();        The error message uses the El method to print out the error message        mv.addobject ("Ex", e);        Determine the exception type if        (e instanceof usernameexception) {            //If it is a usernameexception exception, go to the name.jsp page            mv.setviewname ("name");        if (e instanceof ageexception) {            //If it is a ageexception exception, go to the name.jsp page            mv.setviewname ("Age");        }        Return the View object return        mv;    }}

  

Processor class

Import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.requestmapping;/ * * Created by Administrator on 2018/3/30. */@Controllerpublic class Firstcontroller {    @RequestMapping ("/first") public    string Dofirst (string username, int age) throws Exception {        if (!username.equals ("admin")) {            throw new usernameexception ("User name error");        }        if (age>60) {            throw new Ageexception ("Age error");        }        return "Dosecond";    }}

  

Last Configuration Spring.xml

Configure a custom exception handler for the Bean

      <!--parameter Method name Resolver--   <bean id= "Methodnameresolver" class= " Org.springframework.web.servlet.view.InternalResourceViewResolver ">       <property name=" prefix "value="/ day11selfexception/"/>       <property name=" suffix "value=". jsp "/>   </bean>    <!-- All labeled classes under Scan Package--    <context:component-scan base-package= "cn.happy.day11selfException"/>    <!-- Custom Exception Processor--    <bean class= "Cn.happy.day11selfException.MyHandlerExceptionResolver"/>

  

④ registering exception handlers using annotations

@ExceptionHandler () is used to catch exceptions that occur on the system, and all exceptions are caught by default. It has only one parameter and is an array of class type that can be used to catch exceptions of class type.

Custom exception Classes

Import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.ExceptionHandler ; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.servlet.modelandview;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * Created by Administrator on 2018/3/30. */@Controllerpublic class Firstcontroller {//Capture only Usernameexception and ageexception types of exception @ExceptionHandler ({Usernameexc Eption.class,ageexception.class}) Public Modelandview resolveexception (Exception e) {Modelandview mv=new Model        Andview ();        Mv.addobject ("Ex", e); Determines whether the exception type is a Usernameexception exception if (e instanceof usernameexception) {//the page to go to after an exception occurred Mv.setviewna        Me ("name"); }//To determine if the exception type is ageexception exception if (e instanceof ageexception) {//jump page Mv.setviewname ("Age        ");    }//Return the Model View object return MV; }//url @RequestMapping ("/First ") Public String Dofirst (String Username,int age) throws Exception {if (!username.equals (" admin ")) {        throw new Usernameexception ("User name error");        } if (age>60) {throw new Ageexception ("Age error");    } return "Dosecond"; }}

  

Spring.xml Configuration

<!--parameter Method name Resolver--   <bean id= "Methodnameresolver" class= " Org.springframework.web.servlet.view.InternalResourceViewResolver ">       <property name=" prefix "value="/ day11selfexception/"/>       <property name=" suffix "value=". jsp "/>   </bean>    <!-- All labeled classes under the scan package--    <context:component-scan base-package= "Cn.happy.day12annotationException"/>

  

  

  

  

Springmvc Exception Handling

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.