STRUTS2 (iii) service-side data validation framework in the---struts2 Validate

Source: Internet
Author: User

STRUTS2 provides us with a good data validation framework –validate, which can easily implement data validation on the server side.

 ActionSupport类提供了一个validate()方法,当我们需要在某一个action中进行数据验证时,可以重写这个方法。数据验证往往是在客户端向服务端提交表单信息时进行的,比如execute方法负责处理表单信息并返回相应的结果,在此之前,validate会先对提交的表单信息进行验证:

Validation Pass: The appropriate action for execute is performed.
Authentication failed:
–> defines the return result after a failure: for example, error, the page where error is found in Struts.xml is displayed, and the wrong message is shown in the way you wrote it.
–> The return result is not defined, the default is return input, you need to define the page of input in Struts.xml, otherwise you will get an error.

 需要注意的是,validate会对所有方法都进行数据验证,为了针对某一个方法进行数据验证,可以定义一个方法,方法名为validate+需要验证的方法(首字母大写),比如validateExecute会验证提交给execute的表单数据,validateLogin会验证提交给login方法的表单数据。个人认为尽量不要重写validate方法,而是全部使用validate+方法名的方式来编程。

If a field in the form is not valid, we can return it to the client, which is to be implemented using the Addfielderror ("field name", "error Message") method.
–> this.addfielderror ("name", "nickname length must not be less than 5");
The error message is displayed above the text box for name
–> This.addfielderror ("", "nickname length must not be less than 5");
The error message is not displayed, but if you include the label on the page, the quiz shows that if you write the label inside the form, the error message appears above the entire form.

–> if there's more than one piece of information
This.addfielderror ("name", "nickname length must not be less than 5");
This.addfielderror ("Password", "Password length must not be less than 12");
Or
This.addfielderror ("", "nickname length must not be less than 5");
This.addfielderror ("", "password length must not be less than 12");
It will all be displayed.

Here is an example:

1. The project documents are as follows:

2.web.xml

<?xml version= "1.0" encoding= "UTF-8"?><web-app version= "3.0" xmlns="Http://java.sun.com/xml/ns/javaee"  xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd " >            < display-name></display-name >   <!--Configure Filter class --  < filter>        <filter-name >Struts2</filter-name >       <!--since struts-2.1.3, the Org.apache.struts2.dispatcher.FileDispatcher value has been marked as obsolete and is now written as follows --        <filter-class>Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class >    </filter >    <!--filters are used to initialize STRUTS2 and process all Web requests --    <filter-mapping >        <filter-name >Struts2</filter-name >        <url-pattern >/*</url-pattern >    </filter-mapping >  < welcome-file-list>    <welcome-file >index.jsp</welcome-file >  </ welcome-file-list></Web-app>

3.struts.xml

<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "Http://struts.apache.org/dt Ds/struts-2.0.dtd "><struts>    <!--struts Basic configuration content --    <!--package-name: Used to differentiate between different package, must be unique, available variable name, for other package to inherit; Package-namespace: Used to reduce duplication of code (and Struts1 ), which is the part of the input path when the action is invoked; Package-extends: Used to inherit other package to use the filter inside, etc.    < package name ="struts" namespace= " extends= " Struts-default">     <!--action-name: Used to distinguish different actions in a package; must be a unique, available variable name; Is the part of the input path when the action is invoked; action-class:action In the path (package name + class name); The method name called by Action-method:action; Execute is executed by default, so execute can not write --          <action name ="Login" class="action." Loginaction " method="execute">              <result name ="Success">/welcome.jsp</ result>              <result name ="index">/login.jsp</ result>              <result name ="Input">/login.jsp</ result>          </Action >          <action name ="Index" class="action." Loginaction " method="index">              <result name ="index">/login.jsp</ result>          </Action >    </ Package ></struts>

4.userbean.java

Package Bean; Public classUserBean {//Encapsulates the form item, which is the field in the form, and corresponds to     PrivateString name;PrivateString password;//Encapsulates a non-form item that does not have this attribute in the form, where info is used to store information returned to the page by the server     PrivateString info; PublicStringGetName() {returnName } Public void SetName(String name) { This.     name = name; } PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This.     Password = password; } PublicStringGetInfo() {returnInfo } Public void SetInfo(String info) { This.     info = info; }}

5.loginaction.java

 PackageActionImportBean. UserBean;ImportCom.opensymphony.xwork2.ActionSupport;ImportCom.opensymphony.xwork2.ModelDriven;The /*** Action is used to handle business logic, and, according to layered thinking, the attributes of the entity object should not be placed in the action, so it is encapsulated as an entity bean. * * Instead of using the Bean in action, use Modeldriver (model-driven) and use Modeldriver to inherit the Modeldriven class. ***/Public class loginaction extends actionsupport implements Modeldriven <UserBean>{     PrivateUserBean model;@OverridePublic UserBean Getmodel () {if(model = =NULL) {model =NewUserBean (); }returnModel } public String index () {return "Index"; } public String execute () {//will automatically remove values from the page form          if("SA". Equals ( This. Getmodel (). GetName (). Trim ()) &&"AAAAAA". Equals ( This. Getmodel (). GetPassword (). Trim ())) { This. Getmodel (). SetInfo ("Successful Landing");returnSUCCESS; }Else{ This. Getmodel (). SetInfo ("Login Failed");return "Index"; }     }/** * When executing a method, verify the legality of the data, the method name is the Validate+ method name (capital letter) * Direct write validate will validate all methods */public void Validateexecute () {if( This. Getmodel (). GetPassword (). Trim (). Length () = =0){//Return error message               //* Note: If validation is incorrect and no return string is specified, the default is to return input               //The first parameter can be a page form field, such as Model.password, which appears in the upper part of the text box               ///The first parameter can be displayed on the page via the <s:fielderror/> label if it is empty                  This. Addfielderror ("","Password cannot be empty"); This. Addfielderror ("","Password cannot be empty"); }     }}

6.login.jsp

<%@ Page language ="java" import="java.util.*" pageencoding= " UTF-8"%><%@ taglib prefix ="s" uri="/struts-tags" %><! DOCTYPE html><html>  < head>    <title >Login</title >  </ head>  < body>   <!--to get the information returned after STRUTS2 data validation, you must use the STRUTS2 label--     <s:form Action ="Login">     <S:textfield Label ="login name" name= "model.name" ></S:textfield >     <S:textfield Label ="password" name= "model.password" > </S:textfield >     <s:submit value ="sign in"></ s:submit>     </s:form >     <!--to display all error messages returned by the server Addfielderror method--     <s:fielderror />  </ body></html>

7.welcome.jsp

<%@ Page language ="java" import="java.util.*" pageencoding= "utf-8"%> <%String path = request. Getcontextpath (); String basepath = request. Getscheme () +"://" +request. getServerName () +":" +request. Getserverport () +path+"/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><html>  < head>    <base href ="<%=basePath%>">    <title >Info</title >  </ head>  < body>     <!--writing from request${request.model.name}<br />${request.model.info}<br />     <!--two-value stack (scrutiny after the value stack)--${model.name}<br />${model.info}<br />     <!--abbreviations --${name}<br />${info}<br />  </ body></html>

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

STRUTS2 (iii) service-side data validation framework in the---struts2 Validate

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.