Spring MVC exception handling and log4j configuration

Source: Internet
Author: User
Tags log4j

1. Must be to enter the corresponding LOG4J package: Log4j.x.jar Package

2. Write context in Web.xml

<context-param>
	    <param-name>log4jConfigLocation</param-name>
	   <param-value>/ Web-inf/log4j.properties</param-value>
</context-param><listener><listener-class> Org.springframework.web.context.contextloaderlistener</listener-class></listener>



3. Configure the Log4j.properties property file

################ FATAL, ERROR, WARN, INFO, DEBUG
log4j.rootlogger=warn,stdout,d,e

###
stdout Log4j.appender.stdout=org.apache.log4j.consoleappender
log4j.appender.stdout.target=system.out
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
Log4j.appender.stdout.layout.ConversionPattern =%d{absolute}%5p%c{1}:%l-%m%n ### logFile ### ###
Save error to another file ###
Che.log4j.DailyRollingFileAppender
Log4j.appender.d.file=d:/logs/test-error.log
Log4j.appender.d.append=true #error only in this
file
log4j.appender.d.threshold =warn
Log4j.appender.d.layout=org.apache.log4j.patternlayout
log4j.appender.d.layout.conversionpattern=%-d{ Yyyy-mm-dd HH:MM:SS} [%t:%r]-[%p]  %m%n


4. Write to log

Private final Log logger = Logfactory.getlog (simplercontroller.class);

Logger.warn ("logger");
Logger.error ("~~info~~");



5. Global exception handling configuration, written in X-servlet.xml

<bean id= "Exceptionresolver" class= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" > <property name= "exceptionmappings" > <props> <pro P key= "Java.lang.Exception" >errors/error</prop> <prop key= "java.lang.Throwable" >error s/err</prop> </props> </property> <property name= "Statu     
                 Scodes "> <props> <prop key=" Errors/error ">500</prop> <prop key= "errors/404" >404</prop> </props> &LT;/PROPERTY&G     
         T <!--set the log output level, and do not define error log information such as warnings--> <property name= "warnlogcategory" value= "WARN" ></property > <!--default error page, use this default configuration--> <property name= when the exception corresponding view specified in the above mappings is not found Defaulterrorvi EW "value=" errors/eRror "></property> <!--default HTTP status code--> <property name=" Defaultstatuscode "Valu     e= ></property> </bean> <!--global exception configuration end-->


Spring MVC Exception Handling method

There are two main ways that SPRINGMVC provides exception handling, one is to implement your own handlerexceptionresolver directly, and the other is to use annotations to implement an exception-specific controller-- Exceptionhandler.

1, the realization of their own handlerexceptionresolver,handlerexceptionresolver is an interface, SPRINGMVC itself has a realization of its own- Defaultexceptionresolver, the parser simply intercepts some of the more typical exceptions.

  Java code     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 ");       &nbsp}      }  

The 4th parameter of the above resolveexception represents which type of exception to process, and if you want to process multiple exceptions at the same time, you can replace it with an array of exceptions.

After defining such an exception handler, you define such a Bean object in ApplicationContext, such as: XML code <bean id= "Exceptionresolver class=" Com.tiantian.xxx.web.handler.ExceptionHandler "/>

2, using @exceptionhandler for processing

Using @exceptionhandler for processing there is a bad place to do exception handling methods must be in the same controller as the wrong way.

such as: 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 {                  /**         *          *  @return       for handling exceptions    */        @ExceptionHandler ({myexception.class})        public string exception (myexception e)  {            system.out.println (E.getmessage ());           &nbsP;e.printstacktrace ();            return  "Exception";       &nbsp}                @ Requestmapping ("Test"

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.