Form data verification is an essential part of an application. Generally, form data verification is divided into front-end verification and backend verification, front-end verification uses JS scripts to verify data before submission, and back-end verification is performed after data submission.
For security reasons, backend verification is essential. When the front-end verification fails for some reason, the validity and validity of submitted data can still be ensured due to the existence of backend verification.
There are many backend verification methods, such as configuration file-based verification and annotation-based verification, and many mature verification frameworks. This article introduces a verification method based on Hibernate metadata. I have used it in many projects and the results are very good. I would like to share with you here.
Before applying the verification method mentioned in this article, we should meet the following requirements:
The persistence layer of this program uses Hibernate.
The form on the page corresponds to the database table, and the form data field name is consistent with the database field name.
It is best to use Spring.
In addition, the Hibernate metadata-based validation can only ensure that the fields are empty, the data type is correct, and the field length is consistent with the three rules. As the method mentioned in this Article is to use an interceptor to perform validation at the business layer, it does not conflict with other verification tools and can be effectively complementary.
[Java]
Public class ValidationInterceptor extends HandlerInterceptorAdapter {
@ Resource (name = "& sessionFactory ")
Private LocalSessionFactoryBean sessionFactory;
@ Override
@ SuppressWarnings ("unchecked ")
Public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Final String uri = request. getRequestURI ();
// Find the corresponding validation entity class through the request URI, which needs to be configured externally
Final String entityName = getValidation (uri );
// If no configuration exists, this request does not need to be verified.
If (entityName = null)
Return true;
// Returns the PersistentClass of Hibernate using the object name.
Final PersistentClass clazz = sessionFactory. getConfiguration (). getClassMapping (entityName );
// Metadata of the corresponding table
Final Table table = clazz. getTable ();
Final Iterator <Column> iterator = table. getColumnIterator ();
Final Map <String, String> errors = new HashMap <String, String> ();
While (iterator. hasNext ()){
// Metadata of the corresponding column
Final Column column = iterator. next ();
// Column name
Final String name = column. getName ();
// This is the attribute mapped from the database column to JAVA.
Final Property property Property = clazz. getProperty (name );
// This is the value submitted by the front-end form
Final String value = request. getParameter (name );
// If the value is null, skip the validation of this field
If (value = null)
Continue;
// The verification is not empty.
If (! Column. isNullable () & "". equals (value. trim ())){
Errors. put (name, "field" + name + "value cannot be blank! ");
}
// Verify the string length
Else if (property. getType () instanceof StringType ){
If (value. length ()> column. getLength ()){
Errors. put (name, "field" + name + "is too long! ");
}
}
// Check date type
Else if (property. getType () instanceof DateType ){
Final SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd ");
Try {
Format. parse (value );
} Catch (Exception e ){
Errors. put (name, "field" + name + "must be of the date type! ");
}
}
// Verify the numeric type, including floating point
Else if (property. getType () instanceof BigDecimalType ){
Int precision = column. getPrecision ();
Int scale = column. getScale ();
Int front = precision-scale;
String patten = "";
For (int I = 0; I <front; I ++ ){
Patten + = "#";
}
If (scale> 0 ){
Patten + = ".";
For (int I = 0; I <scale; I ++ ){
Patten + = "#";
}
}
Final NumberFormat format = new DecimalFormat (patten );
Try {
Format. parse (value );
} Catch (Exception e ){
Errors. put (name, "field" + name + "must be a number (" + patten "+ ")! ");
}
}
}
// If no error exists, allow it directly.
If (errors. isEmpty ())
Return true;
// If there is an error, a JSON string describing the error message will be generated and the frontend will be returned.
Response. setContentType ("text/json; charset = UTF-8 ");
Response. getWriter (). write (JSONObject. fromObject (errors). toString ());
Response. getWriter (). close ();
Return false;
}
}
Each URL needs to map the entity class used for data verification. You can use a Propertes file for configuration. The getValidation method in the code needs to retrieve information from this configuration file.
[Java]
/Test/save_log.do = com. coolfancy. blog. entity. Log
/Test/save_reply.do = com. coolfancy. blog. entity. Reply
After this method is used, the database metadata-based verification does not need to be written in the program. You can use this Interceptor to complete the verification. If there are other complicated verifications, you can use the original verification method in Action to continue verification.
By fancy888