Springmvc Exception Handling

Source: Internet
Author: User

In order to deal with the exception that occurs during the operation of the code, give the user a more friendly exception interface, need to introduce SPRINGMVC exception handling function, in order to demonstrate this function, this paper realizes a more common requirement.

all exceptions are categorized into two categories, one of which is the exception class created by the programmer himself, and the other is the exception class defined by the system or framework. The programmer himself defines the exception class to output exception information on the interface, and the system-defined exceptions all uniformly output "Unknown error".
Throws an exception, jumps to the exception page, and reads seconds, automatically jumps to the page where the request occurred after three seconds, or a page that is defined by the programmer.

In order to implement this function, first write your own exception class, I named MyException here, and add two member variable message and destination, respectively, to represent the exception information and the exception page automatically jump to the target page.
In which you add getter, setter, and constructor methods, the program list is as follows:

 PackageCom.elin4it.ssm.controller.exception;/** * description:myexception * Author:elin Zhou * create:2015-07-04 13:49 * * Public  class myexception extends Exception {    PrivateString message;//The position of the jump after the exception is generated, the default jumps to the previous page    PrivateString destination; Public myexception(){} Public myexception(String message) {Super(message); This. message = message; } Public myexception(String message,string destination) {Super(message); This. Destination = destination; This. message = message; } PublicStringgetdestination() {returnDestination } Public void setdestination(String destination) { This. Destination = destination; }@Override     PublicStringGetMessage() {returnMessage } Public void Setmessage(String message) { This. message = message; }}

The ability to handle exceptions, SPRINGMVC provides a handlerexceptionresolver interface for programmers, as long as the Resolveexception method is implemented, that is, the method can be called when an exception occurs to handle the exception.
So create a class that implements the Resolveexception interface and adds

publicresolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)

Method.

The handling of specific exceptions is not mentioned here, the main purpose of this article is to introduce the process of exception handling, the specific business logic according to the actual situation, this is only posted in order to complete the above requirements to achieve the code.

 PackageCom.elin4it.ssm.controller.exception;ImportOrg.springframework.web.servlet.HandlerExceptionResolver;ImportOrg.springframework.web.servlet.ModelAndView;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * description:myexceptionresolver * Author:elin Zhou * create:2015-07-04 13:49 * * Public  class myexceptionresolver implements handlerexceptionresolver {    @Override     PublicModelandviewresolveexception(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception e) {MyException myexception =NULL;if(EinstanceofMyException) {//If the exception received is a user-defined exceptionMyException = (myexception) e; }Else{//If an exception is accepted for another system-defined exceptionMyException =NewMyException ("Unknown error"); }if(myexception.getdestination () = =NULL){//If the target page after the exception occurs is not specified, automatically jumps to the page that originated the request            //Get the full path to the originating request, such as Http://localhost:8080/ssm/book/bookIndexString Requesturl = Httpservletrequest.getheader ("Referer");//Divide the path according to '/'string[] Splitfromurl = Requesturl.split ("/");//Number of sub-strings to get split            intCount = Splitfromurl.length;//Get the last two terminal strings and stitch them into logical addressesString Destination = splitfromurl[count-2]+"/"+splitfromurl[count-1];        Myexception.setdestination (destination); } Modelandview Modelandview =NewModelandview ();//Send exception to request for interface output JumpModelandview.addobject ("Exception", myexception); Modelandview.setviewname ("Error");returnModelandview; }}

The code above is based on the parameters to determine what kind of exception, if the system is defined to create a myexception, and the message is assigned a value of "Unknown error." Then determine if the destination is null, and if so, assign it to the page where the user requested it. It is then assigned to Modelandview and then returned.

Finally, you need to configure the exception handler to SPRINGMVC and add the processor class injection to the SPRINGMVC configuration file.

class="com.elin4it.ssm.controller.exception.MyExceptionResolver"/>

No need to write the ID or configure additional information, SPRINGMVC when loading the bean to the IOC container, if you scan to a class that implements the Handlerexceptionresolver interface, use it as an exception handler.

Finally paste the test controller method and exception handling JSP page

 @RequestMapping  ( "/addbook" ) public  string  Addbook  () throws  exception{//test custom exceptions  Span class= "Hljs-keyword" >if  (1  ==1 ) Span class= "Hljs-keyword" >throw  new  myexception (     "test Exception" );    //test system-defined exception     int  a = 10 /0 ; return   "Book/addbook" ;}  
<%--Created by IntelliJ idea. User:elin Date:  7-4Time: PM 1: To Change this template use File | Settings | File templates.--%>    <%@ page contenttype="Text/html;charset=utf-8" language="java" %><html><head>  <title>Error occurred</title>  <script type="Text/javascript">  function countdown(Secs,surl){var jumpto =      document.getElementById (' Jumpto ');      Jumpto.innerhtml=secs; if (--secs>0)      {SetTimeout ("Countdown" ("+secs+","+surl+" ') ",+);        } else{location.href=surl; -MA}}          </script></head><body>  <H1>${exception.message}</H1>  <a href="<%=request.getcontextpath ()%>/${exception.destination}" ><span id="Jumpto">3</span>Seconds, the system will automatically jump, or click here to jump directly</a>  <script type="Text/javascript">Countdown (3,' <%=request.getcontextpath ()%>/${exception.destination} '); </script></body></html>

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.