SpringMVC Learning Series-postscript combined with SpringMVC and Hibernate-validator, based on the background verification rules, the front-end JavaScript verification code is automatically generated, springmvcvalidator

Source: Internet
Author: User

SpringMVC Learning Series-postscript combined with SpringMVC and Hibernate-validator, based on the background verification rules, the front-end JavaScript verification code is automatically generated, springmvcvalidator

In SpringMVC Learning Series (6), we have learned how to use Hibernate-validator to verify the data legality in the background. However, background verification is generally only the second insurance, for better user experience, JavaScript verification will be performed on the front end. After the verification is passed, the data can be submitted to the backend. Therefore, we must inevitably write the corresponding js verification code on the front-end page.

However, this requires some troublesome and repetitive operations:

1. First, ensure that the verification rules of the front-end and back-end are the same, so as to avoid the case that the front-end verification passes and the verification fails after submission.

2. Ensure that the verification rules of the front-end and back-end are synchronized, that is, the verification rules of the other side must be modified after the verification rules of the other side are modified.

3. Ensure that the error message is consistent with the corresponding international problem. (In fact, this problem can be solved when an error message is prompted in the js verification code. binding the international information can solve this problem, but it is cool .)

Okay ~~~ These are not the main reasons. The main reason is that I am too lazy to write the corresponding js verification code one by one on each page, so how can we make the backend automatically generate the front-end js verification code according to the model verification rules we define?

The following steps are taken:

First, I want to use the form label of spring mvc <form: form modelAttribute = "contentModel" method = "post">, so that the corresponding front-end code can be generated by specifying it, which is concise and elegant, how cool !, Then we need to customize the taglib label first.

1. Add a class named JsValidateTag. I defined it under the com. demo. test package.

2. Add an xml file under the WebContent/WEB-INF directory. Here I name it test. tld content as follows:

<?xml version="1.0" encoding="UTF-8"?><taglib xmlns="http://java.sun.com/xml/ns/j2ee"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"        version="2.0">                <description>Test</description>        <tlib-version>1.0</tlib-version>        <short-name>test</short-name>        <uri>http://www.mytest.org/tags/test</uri>                <tag>            <description></description>            <name>jsValidate</name>            <tag-class>com.demo.test.JsValidateTag</tag-class>            <body-content>empty</body-content>            <attribute>                <description>Path to property for data binding</description>                <name>modelAttribute</name>                <required>true</required>                <rtexprvalue>true</rtexprvalue>            </attribute>        </tag>        </taglib>

The above content is very simple. It defines a label named jsValidate. The corresponding class is com. demo. test. JsValidateTag, which we created earlier, and then there is a parameter named modelAttribute.

3. Implement the specific processing logic in the newly created class. The Code is as follows:

 

Package com. demo. test; import java. lang. reflect. field; import java. util. arrayList; import java. util. hashMap; import java. util. iterator; import java. util. list; import java. util. map; import java. util. map. entry; import javax. servlet. jsp. jspException; import org. hibernate. validator. constraints. email; import org. hibernate. validator. constraints. notEmpty; import org. hibernate. validator. constraints. range; import org. s Pringframework. web. servlet. tags. form. abstractFormTag; import org. springframework. web. servlet. tags. form. tagWriter;/*** automatically generate front-end js Verification Code * @ author liukemng@sina.com ***/@ SuppressWarnings ("serial") public class JsValidateTag extends AbstractFormTag {@ SuppressWarnings ("unused ") private TagWriter tagWriter; private String modelAttribute; public void setModelAttribute (String modelAttribute) {this. modelAt Tribute = modelAttribute;} public String getModelAttribute () throws JspException {String resolvedModelAttribute = (String) evaluate ("modelAttribute", this. modelAttribute); return (resolvedModelAttribute! = Null? ResolvedModelAttribute: "") ;}@ Override protected int writeTagContent (TagWriter tagWriter) throws JspException {Object model; if (getRequestContext (). getModel ()! = Null) model = getRequestContext (). getModel (). get (getModelAttribute (); else model = this. pageContext. getRequest (). getAttribute (getModelAttribute (); if (model! = Null) {Map <String, List <String []> fieldValidateMap = new HashMap <String, List <String []> (); try {Field [] theFields = model. getClass (). getDeclaredFields (); if (theFields! = Null & theFields. length> 0) {for (Field field: theFields) {String fieldName = field. getName (); List <String []> fieldValidateList = new ArrayList <String []> (); NotEmpty notEmpty = field. getAnnotation (NotEmpty. class); if (notEmpty! = Null) {String messageName = notEmpty. message (); fieldValidateList. add (new String [] {"required", "true", getRequestContext (). getMessage (messageName. substring (1, messageName. length ()-1)});} Email email = field. getAnnotation (Email. class); if (email! = Null) {String messageName = email. message (); fieldValidateList. add (new String [] {"email", "true", getRequestContext (). getMessage (messageName. substring (1, messageName. length ()-1)});} Range range = field. getAnnotation (Range. class); if (range! = Null) {String messageName = range. message (); fieldValidateList. add (new String [] {"range", "[" + range. min () + "," + range. max () + "]", getRequestContext (). getMessage (messageName. substring (1, messageName. length ()-1)});} if (fieldValidateList. size ()> 0) {fieldValidateMap. put (fieldName, fieldValidateList) ;}}} catch (SecurityException e1) {e1.printStackTrace () ;}if (fieldValidateMap. size ()> 0) {StringBuilder rulesBuilder = new StringBuilder (); StringBuilder messagesBuilder = new StringBuilder (); rulesBuilder. append ("rules: {"); messagesBuilder. append ("messages: {"); int I = 0; Iterator <Entry <String, List <String []> iterator = fieldValidateMap. entrySet (). iterator (); while (iterator. hasNext () {Entry <String, List <String []> entry = iterator. next (); rulesBuilder. append (entry. getKey ()). append (": {"); messagesBuilder. append (entry. getKey ()). append (": {"); int j = 0; for (String [] array: entry. getValue () {rulesBuilder. append (array [0]). append (":"). append (array [1]); messagesBuilder. append (array [0]). append (":\""). append (array [2]). append ("\" "); if (j <entry. getValue (). size ()-1) {rulesBuilder. append (","); messagesBuilder. append (",");} j ++;} rulesBuilder. append ("}"); messagesBuilder. append ("}"); if (I <fieldValidateMap. size ()-1) {rulesBuilder. append (","); messagesBuilder. append (",");} I ++;} rulesBuilder. append ("},"); messagesBuilder. append ("}"); tagWriter. startTag ("script"); tagWriter. writeAttribute ("type", "text/javascript"); tagWriter. appendValue ("$ (function () {"); tagWriter. appendValue ("$ (\" # "); tagWriter. appendValue (getModelAttribute (); tagWriter. appendValue ("\"). validate ({"); // verify tagWriter when the focus is lost. appendValue ("onfocusout: function (element) {$ (element ). valid () ;}, "); tagWriter. appendValue (rulesBuilder. toString (); tagWriter. appendValue (messagesBuilder. toString (); tagWriter. appendValue ("});"); tagWriter. appendValue ("});"); tagWriter. endTag (true) ;}} this. tagWriter = tagWriter; return EVAL_BODY_INCLUDE;} @ Override public void doFinally () {super. doFinally (); this. tagWriter = null ;}}

 

4. Next, reference our custom tag in the page:

<%@ taglib prefix="test" uri="http://www.mytest.org/tags/test" %>

And specify the model name:

<test:jsValidate modelAttribute="contentModel"></test:jsValidate>

The overall page content is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%@ taglib prefix="test" uri="http://www.mytest.org/tags/test" %>

Run the test to see the effect:

 

Aha Haha ~~~, It has been generated, and you no longer need to write verification rules yourself. The laziness condition is aggravated ~~~

 

Note: The above Code only implements js verification rules corresponding to @ NotEmpty, @ Range, and @ NotEmpty annotations, add the corresponding logic to the JsValidateTag class for js verification rules of other annotations.

 

Project source code download: http://pan.baidu.com/s/1c0pVzFy

 

Reserve the copyright. If you need to repost it, please indicate the source...

 

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.