A detailed explanation of data checksum exception handling in SPINGMVC

Source: Internet
Author: User

*springmvc Use the JSR-303 checksum specification, JSR-303 is the JAVAEE6 specification.
SPRINGMVC specifically uses the Hibernate-validator check frame (which is not related to hibernate ORM), based on the Bean's attribute checksum. *
So you need to import the jar package:

Implementation of data validation in 1:SPRINGMVC

1.1 Annotation Usage: for specific reference: Hibernate Official Document: Http://docs.jboss.org/hibernate/validator/4.2/reference/zh-CN/html_ single/#validator-usingvalidator

Briefly introduced below:


1.2 With bean checksum, the required configuration needs to be configured in SPRINGMVC:

If you do not use a configuration file to write error messages directly in the annotations, you need to configure the validator<!--config Bean validator--<bean id= "Validator" class=" Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean ">       <!--validators --</Bean>Then reference it in the MVC annotation driver.<mvc:annotation-drivenValidator="Validator"/>  <context:component-scan base-package="Com.leige.controler" />If you use the error profile to use placeholders in annotations, the replacement error message is configured as follows:<!--config Bean validator--<bean id= "Validator" class=" Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean ">       <!--validators --        < property name= "providerclass" value=" Org.hibernate.validator.HibernateValidator " />        <!--Specifies the resource file used by the checksum, and if not specified, validationmessages.properties by default with Classpath        < property name= "validationmessagesource" ref=" Messagesource " />    </Bean>    <!--check error message profile --    <bean id= "messagesource"class=" Org.springframework.context.support.ReloadableResourceBundleMessageSource ">                <!--resource file name --        < property name="Basenames">            <list>                <!--error configuration information, be careful not to write the file suffix studentvalidationmessages.properties, this error, I adjusted for two hours fuck don't write -            <value>Classpath:studentvalidationmessages</value>          </list>           </Property >        <!--resource file encoding format --        < property name="fileencodings" value="Utf-8" />        <!--cache time for resource file content, in seconds--        < property name="Cacheseconds" value=" />" </Bean>You can then refer to:<mvc:annotation-drivenValidator="Validator"/>  <context:component-scan base-package="Com.leige.controler" />

In the Bean field using the annotation check, here together to talk about, packet check, configuration file check, but also hope that you can accept:

 Public  class Student {    PrivateInteger SID;/** * Data check error message can be written directly in the annotation (@NotNull (message= "name is not nullable") @Size(min=3,max=15,message= "name must be between 3-15"))     *, can also be written in the configuration file such as ( @NotNull(message= "${student.error.age.null}"), using placeholders instead of * if you first want to load the configuration file in Springmvc, read the error message *      */    @NotNull(message="{student.name.null}", groups= (Validation1.class))@Size(min=3, max= the, message="{student.name.size}", groups= (Validation1.class))PrivateString name;@NotNull(message="{student.age.null}", groups= (Validation1.class))PrivateInteger age;    Setter.. Getter ...}

The packet check uses the interface to differentiate, cannot use the class, the interface does not need to write, only has the function of distinguishing, indicates which group the check rule uses, groups can also specify multiple groups simultaneously

Apply validation rules in Controler

    /** * @param model * @param student * @param bindingresult * @Validated     and Bindingresult is paired with, * position to be fixed, @Validated in front of the checked Po object, * Bindingresult is used to receive the checksum error message, to be placed behind the verified object. * @Validated(value= (validation1.class) specifies which group to apply */    @RequestMapping("/insert.action") PublicStringinsertstudent(@Validated(Value= (Validation1.class)) Student Student,bindingresult Bindingresult,model Model) {if(Bindingresult.haserrors ()) {//If the checksum is faulted, an error message is displayed, and the EchoModel.addattribute ("Errors", Bindingresult.getallerrors ());//Return to original page            return "Insert"; }Else{Studentservice.insert (student);//Successful return to Success page            return "Success"; }    }

Page display code:

<form action="${pagecontext.request.contextpath}/student/insert.action"Method="POST">name<inputtype="Text"Name="Name"Value="${student.name}"><br/>age:<inputtype="Text"Name="Age"Value="${student.age}"><br/><inputtype="Submit"Value="Add"> forEach items="${errors}"Var="Err">${err.defaultmessage}&LT;/C: forEach>

Demo Result:

Exception handling Process in 2:SPRINGMVC:


2.1 Therefore, exception handling first creates a custom exception

package com.leige.exception;publicclass StudentException extends Exception {    //接收异常信息    publicStudentException(String message) {        super(message);    }}

2.2 Creating the exception handler for the custom exception

 PackageCom.leige.exception.handler;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.web.servlet.HandlerExceptionResolver;ImportOrg.springframework.web.servlet.ModelAndView;ImportCom.leige.exception.StudentException;/** * @author Custom exception handlers need to implement SPRINGMVC exception handling interface Handlerexceptionresolver * */ Public  class Studentexceptionhandler implements handlerexceptionresolver {     @Override     PublicModelandviewresolveexception(HttpServletRequest request, httpservletresponse response, Object handler, Exception ex) {//TODO auto-generated method stub        //Judging the type of exceptionModelandview modelandview=NewModelandview ();if(exinstanceofstudentexception) {studentexception studentexception= (studentexception) ex;//Handling Custom exceptionsModelandview.addobject ("Error", Studentexception.getmessage ()); }Else{//If it is runtime exception, prompt for exception information, for example: Website busy, please connect laterModelandview.addobject ("Error","website busy, please connect later"); }//Set Exception pageModelandview.setviewname ("Web-inf/jsp/error");returnModelandview; }}

2.3 Creating an exception page it goes without saying.

2.4 To configure the exception handler in Springmvc, simply add the following configuration:

<!-- 异常处理器 ,配置你的自定义异常处理器--><bean class="com.leige.exception.handler.StudentExceptionHandler"></bean>

Test you can test yourself, here is not the demonstration, exception handling mechanism and STRUTS2 have a lot of places are similar \

The most important point to note:

Note that
* Exception handlers can configure multiple
The purpose of configuring multiple exception handlers is to handle each exception type separately, and SPRINGMVC executes the exception handler in the configured order, but it is important to note that other exception handlers return null, except for the last exception handler, which returns Modelandview. SPRINGMVC source code is as follows: *

A detailed explanation of data checksum exception handling in SPINGMVC

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.