Annotation-based verification for Java Web simple mall project (6)

Source: Internet
Author: User

Annotation-based verification for Java Web simple mall project (6)

Next to the Java Web simple mall project (V), this article uses the BeanUtil framework to write the registration page and learns Annotation-based verification.

I. registration page 1. Ideas

According to the MVC design in the previous article, our UserServlet is only responsible for processing requests, while BaseServlet is only responsible for calling the method for processing the request

2. Implementation

First, create a registration page for register. jsp. It is very simple. You only need the user name, password, and nickname. Of course, password verification requires you to process it on the server side, and the Annotation at the end will do this.

<%@ page="" contenttype="text/html;charset=UTF-8" language="java">
<% @ Page = "" contenttype = "text/html; charset = UTF-8" language = "java">

2. server-side Processing

First for user. do? Method = register: If this request corresponds, We need to write a register in UserServlet to display the interface

/*** Jump to the registration user Interface */public String register (HttpServletRequest req, HttpServletResponse resp) {// directly return to the current page. Other BaseServlet processes return "user/register. jsp ";}

When we click submit, the submitted action is user. do? Method = add, so we need to write an add method in UserSerclet to add users, and then add users to jump to the user list

/*** Receive registration message, add user * @ return user list */public String add (HttpServletRequest req, HttpServletResponse resp) {String username = req. getParameter ("username"); String password = req. getParameter ("password"); String nickname = req. getParameter ("nickname"); User u = new User (); u. setUsername (username); u. setPassword (password); u. setNickname (nickname);/*** use the dao factory to produce dao. The factory has cache effect. Dependency injection has been used before, so this is not required */// UserDao userDao = (UserDao) PropertiesFactory. getInstance (). createDao ("UserDao"); userDao. add (u); // client jump here. If it is a server, the system submits return "client: user. do? Method = list ";}

Here, the return method uses client jump, because when we jump to the user list, we need to change the URL of the browser.

3. Use BeanUtil for Optimization

From the code above, we can see that when we receive parameters, we need to obtain the parameters first, and then set them one by one. If we want to add an attribute to the User in the future, therefore, it is very difficult to change it, so we need to use reflection for a unified deployment, that is, using BeanUtil.
* The first step is to introduce the package.

* For convenience, write a RequestUtil file and write the processing method.

Import org. apache. commons. beanutils. beanUtils; import javax. servlet. http. httpServletRequest; import java. lang. reflect. invocationTargetException; import java. util. map; import java. util. set;/*** Created by nl101 on 2016/3/5. */public class RequestUtil {/*** automatically creates an instance based on clz, call the set method to set the parameters in req to * @ param clz. The class * @ param req parameter of the instance to be created * @ return returns the created instance */public static Object. setParams (Class clz, httpServletRequest req) {Map
  
   
Maps = req. getParameterMap (); // get the map Set of parameters
   
    
Keys = maps. keySet (); // The collection Object o that obtains the key = null; try {o = clz. newInstance (); // obtain the instance // loop traversal parameter for (String key: keys) {String [] arrs = maps. get (key); // get the parameter value array if (arrs. length> 1) {// If the array length is greater than 1, multiple values are described as BeanUtils. copyProperty (o, key, arrs);} else {// If the array is not greater than 1, set a single value BeanUtils. copyProperty (o, key, arrs [0]) ;}} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} catch (InvocationTargetException e) {e. printStackTrace ();} return o; // return the created object }}
   
  

How can we modify the add method of our UserServlet after writing it?

/*** Receive registration message, add user * @ return user list */public String add (HttpServletRequest req, HttpServletResponse resp) {// directly call its method to create an object. You can use User u = (User) RequestUtil. setParams (User. class, req); userDao. add (u); // client jump here. If it is a server, refresh the page and submit return "client: user. do? Method = list ";}

Is it much less than the amount of code before it is used.

4. Other BeanUtil usage

BeanUtil cannot parse some types, that is, it cannot directly set parameters. for example, for the Date class, there are too many formats for the Date class, so BeanUtil does not know which one to use. In this case, we need to manually write the converter and add it to the BeanUtil rule.

The Converter must implement the org. apache. commons. beanutils. Converter interface and rewrite the convert method.

Import org. apache. commons. beanutils. converter; import java. text. parseException; import java. text. simpleDateFormat;/*** Created by nl101 on 2016/3/5. */public class DateConvert implements Converter {private SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");/*** date Converter, resolve the Date to a special format * @ param aClass use this Class to parse * @ param o parameters to be parsed * @ return returns the parsed Date instance */@ Override public Object convert (Class aClass , Object o) {try {if (o! = Null &&! "". Equals (String) o) {// if the value is not null, return sdf is converted. parse (String) o) ;}} catch (ParseException e) {System. out. println ("date conversion failed"); e. printStackTrace ();} return null; // If the conversion fails, return null }}

Use this converter

User u = new User (); ConvertUtils. register (new DateConvert (), Date. class); // register the converter. When BeanUtil encounters a parameter whose Date is set, it will call this converter try {BeanUtils. copyProperty (u, "date", "1999-10-1");} catch (IllegalAccessException e) {e. printStackTrace ();} catch (InvocationTargetException e) {e. printStackTrace ();} System. out. println (u. getDate (). toString ());


This completes a custom converter.

2. Annotation-based server Verification

When user information is input to the server, it must be verified whether the information is valid before it can be stored in the database; otherwise, it must be entered again.

1. First, let's talk about the desired effect.


The Annotation above the variable has its check type. If it is NOTNULL, it checks whether it is NULL. errsMsg indicates the prompt information, that is, the information to be displayed when it is NULL.

2. The specific implementation process requires an enumeration type to save various verification information. In this simple definition, NOTNULL indicates whether to be null, LENGTH indicates the minimum LENGTH, and NUM indicates whether to be a number.
public enum ValidType {    NOTNULL,LENGTH,NUM;}
The next step is to define Annotation. This is very simple.
// This description refers to the @ Retention (RetentionPolicy. RUNTIME) public @ interface ValidCheck {public ValidType type (); // indicates the Error type public String errsMsg (); // indicates the error message}
Then, because this is the verification of the Request Parameters, You can uninstall the RequestUtil class.
The implementation idea is to get the specified Annotation of the variable, then judge its ValidType, and write a judgment function for each ValidType. If yes, this method is called directly. If yes, the related information is stored in the map set, and then stored in the req, so that the page can obtain information and display it.
/*** Check the parameters, check whether it meets the defined rule * @ param clz the Class corresponding to the parameter to be checked * @ param req parameter information * @ return true */public static boolean isChecked (Class clz, httpServletRequest req) {Field [] fields = clz. getDeclaredFields (); // obtain all attributes boolean isValid = true; // indicates the check result Map
    
     
Errors = new HashMap <> (); // stores the error message req. setAttribute ("errors", errors); // set it to req, so that jsp can get the relevant value // start traversing for (Field f: fields) {if (f. isAnnotationPresent (ValidCheck. class) {// if this Annotition ValidType = f. getAnnotation (ValidCheck. class ). type (); // obtain type String msg = f. getAnnotation (ValidCheck. class ). errsMsg (); // obtain msg if (type = ValidType. NOTNULL) {// if (! IsNotNull (f. getName (), req) {isValid = false; errors. put (f. getName (), msg); // Save the error to it }}} return isValid ;} /*** determine whether it is null * @ param field the attribute name to be judged * @ param req parameter set * @ return true not blank */private static boolean isNotNull (String field, httpServletRequest req) {String temp = req. getParameter (field); if (temp = null | "". equals (temp. trim () {return false;} return true ;}
    
3. Call

The call is very simple. We can check before performing database operations.

/*** Receive registration message, add user * @ return user list */public String add (HttpServletRequest req, HttpServletResponse resp) {boolean isValid = RequestUtil. isChecked (User. class, req); // judge if (! IsValid) {return "user/register. jsp ";} ConvertUtils. register (new DateConvert (), Date. class); // register the converter. When BeanUtil encounters a parameter whose Date is set, it will call this converter User u = (User) RequestUtil. setParams (User. class, req); userDao. add (u); // client jump here. If it is a server, refresh the page and submit return "client: user. do? Method = list ";}
4. jsp page settings

There are two requirements for jsp page settings. The information is displayed only after the jsp page is submitted. If it does not meet the requirements, the information is displayed. In addition, you must save the data filled in before and enter it automatically. At this time, EL's It is easy to use, {} By default, content is displayed, and no content is displayed.

<%@ page="" contenttype="text/html;charset=UTF-8" language="java"><[email protected] prefix="c" uri="http://java.sun.com/jstl/core_rt">
<% @ Page = "" contenttype = "text/html; charset = UTF-8" language = "java"> <[email protected] prefix = "c" uri = "http://java.sun.com/jstl/core_rt">

The framework is almost completed. The next article will gradually improve each step and use blogs to record your experiences.

Related Article

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.