Our website is to interact with users, and the most important way of interaction is the input and output of data. But for the user, the input is not in the form we expect. This is the need to verify the format of the data input by the user, which is the so-called data verification.
In fact, the meaning of data verification is to ensure that the data entering the background is safe!
In most cases we use JavaScript to validate the input data, but this method has limitations
As shown in the figure: We can directly transfer the data to the background by using url splicing, and the data verification at this time is meaningless.
Therefore, js alone cannot meet our security requirements.
At present, the mainstream web layer frameworks have the relevant functions of verification. Our Struts2 provides two relatively simple verification methods:
- Hard-coded way - easy to understand, not easy to maintain
- xml configuration method --- easy to maintain, easy to manage, and not to invade the source code ( recommended )
Let's take a registration as an example to explain the two-way verification process
The data we want to verify is:
Username: The request cannot be empty! More than 6 bits and less than 11 bits
Password: The request cannot be empty! More than 6 digits and less than 11 digits, the two passwords are the same
Age: 0-150 years old required
Email: The request cannot be empty! Must match email format
Phone: Request cannot be empty! Must be in phone format ( 1(3/5/8)xxxxxxxx , or 010-xxxxxxxx or 0531-xxxxxxxx)
First we use hard-coded verification
Hard-coded implementation steps:
Step 1: Create a Struts2 project
Step 2: Write a normal form
The third step : adding tag library support in jsp
Step 4 : Two kinds of verification level errors provided by the struts2 verification framework are added to the jsp :
Property-level errors: <s:fielderrorcssStyle="color:red;"/>
Action -level errors: <s:actionerrorcssStyle="color:red;"/>
Usually attribute validation fails, we put the error information into the fielderror object, and the action-level error information into the actionerror object.
Step 5 : Create an Action class and configure it in struts.xml
Note that a result must be configured , the name value is input , which is used to verify the failure to jump to the page
Step 6 : Create a verification method in the Action class, the method naming rules:
validate+ name of the method to be validated (capitalized)
(For example: execute () method, validation method validateExecute ())
If there are many methods in the action , it can also be verified separately.
Step 7 : Improve the specific judgment in the verification method
There are two types of error messages: FieldError and ActionError
Put the error message into the Field field:
this.addFieldError("username","Username cannot be empty");
Put the error message in the Action field:
this.addActionError("The password must be the same twice");
实际上会将错误信息放入Struts2默认栈队map集合中
页面可以使用 ${errors.username[0]}来单独展示属性错误信息
复杂验证例如邮箱、电话等判断需要用到正则表达式!
用到的界面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>index</title> </head> <body> <s:fielderror cssStyle="color: red"/><br> <s:actionerror cssStyle="color: red;"/><br> <hr/> <form method="post" action="ch07RegisterAction.action"> <%--错误信息内部存储方式是数组,为防止一个表单元素有多个属性--%> <%--对象方式页面错误信息的编写方式有所不同--%> 账号:<input type="text" name="users.username"/>${errors["users.username"][0]}<br> 密码:<input type="password" name="users.password"/>${errors["users.password"][0]}<br> 重新输入密码:<input type="password" name="users.repassword"/>${errors["users.repassword"][0]}<br> E-mail:<input type="text" name="users.email"/>${errors["users.email"][0]}<br> 手机号:<input type="text" name="users.phonenumber"/>${errors["users.phonenumber"][0]}<br> 年龄:<input type="text" name="users.age"/>${errors["users.age"][0]}<br> <input type="submit" value="提交"/> </form> </body> </html>
ValidateAction类
package cn.lovepi.chapter07.action; import com.opensymphony.xwork2.ActionSupport; import java.util.regex.Pattern; /** * * 数据校验示例——硬编码格式 */ public class ValidateAction extends ActionSupport{ private String username; private String password; private String repassword; private String email; private String phonenumber; private int age; @Override public String execute() throws Exception { return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhonenumber() { return phonenumber; } public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }Configure the current Action
<package name="chapter07" extends="struts-default"> <!--Hard-coded configuration data check--> <action name="ch07ValidateAction" class="cn.lovepi.chapter07.action.ValidateAction"> <result name="success">/chapter07/index.jsp</result> <!--必须配置,用于数据校验出错时跳转--> <result name="input">/chapter07/index.jsp</result> </action> </package>ValidateAction 类种对应的校验方法
public void validateExecute(){ if (null==username || username.length()<6 ||username.length()>10) { this.addFieldError("username", "username has error"); } if (null==password || password.length()<6||password.length()>10) { this.addFieldError("password", "password has error"); }else if (null==repassword || repassword.length()<6||repassword.length()>10) { this.addFieldError("repassword", "repassword has error"); }else if(!password.equals(repassword)){ this.addFieldError("password", "tow password is not be same"); } if (age<=0 ||age>150) { this.addFieldError("age", "年龄不符合人类规范!"); } //验证邮箱! [email protected] //只允许a-z A-Z 1-9 -_ //正则表达式---专门用于复杂字符判断的技术。可以应用于所有软件编程语言 Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$"); if (null==email || !p.matcher(email).matches()) { this.addFieldError("email", "邮箱验证失败!"); } Pattern p1=Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{7,8})|(0\\d{3}-\\d{7,8})$"); if (null==phonenumber || !p1.matcher(phonenumber).matches()) { this.addFieldError("phonenumber", "电话格式不正确!"); this.addActionError("action级别错误!"); //这些错误信息被默认放入struts2默认的栈队中。Map集合errors } }
xml配置方式校验
Xml配置方式实现步骤:
第一步:创建Struts2项目,创建实体类Users
第二步:编写一个普通表单
第三步:在jsp中加入Struts2标签库支持
第四步:jsp中加入Struts2校验框架提供了两种校验级别错误:
属性级错误: <s:fielderrorcssStyle="color:red;"/>
Action级错误:<s:actionerrorcssStyle="color:red;"/>
单属性方式页面错误信息:${errors.username[0]}
对象方式页面错误信息:${errors["user.username"][0]}
Step 5: Create an Action class and configure it in struts.xml
Note that a result must be configured , the name value is input , which is used to verify the failure to jump to the page
RegisterAction class
Step 6: Create an Xml configuration file under the action class package , which is used to write verification information
Naming rules: ActionName -validation.xml (Example: UserAction-validation.xml)
Step 7: Write UserAction-validation.xml verification information
User class
public class Users { private String username; private String password; private String repassword; private String email; private String phonenumber; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepassword () { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhonenumber() { return phonenumber; } public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }The interface used is the same as above
RegisterAction class
public class RegisterAction extends ActionSupport{ private Users users; @Override public String execute() throws Exception { return SUCCESS; } public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } }
配置文件编写
<package name="chapter07" extends="struts-default"> <!--xml配置数据校验--> <action name="ch07RegisterAction" class="cn.lovepi.chapter07.action.RegisterAction"> <result name="success">/chapter07/success.jsp</result> <result name="input">/chapter07/index.jsp</result> </action> </package>UserAction-validation.xml 校验信息
<?xml version="1.0" encoding="UTF-8"?> <!--注意这里的代码在对应的/lib/xwork-core.jar/xwork-validator-1.0.3.dtd中 使用1.0.2执行报错--> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> <!--具体需求验证代码--> <validators> <!--对username属性进行验证--> <field name="users.username"> <!--具体验证器,验证属性不能为空--> <field-validator type="requiredstring"> <!--去空格--> <param name="trim">true</param> <!--错误信息--> <message>用户名不能为空</message> </field-validator> <!--使用正则表达式进行验证,验证账户名只能为数字或字母,并且长度在6-25之间--> <field-validator type="regex"> <param name="regex"> <![CDATA[(\w{6,25})]]> </param> <message>账号只能是数字或字母,并且长度得在6-25之间</message> </field-validator> </field> <!--对password属性进行验证--> <field name="users.password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>密码不能为空</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">18</param> <message>密码长度得在6-18位之间</message> </field-validator> <!--注意这里得用fieldexpression来比较两个属性之间的关系--> <field-validator type="fieldexpression"> <param name="expression"> <![CDATA[(users.password==users.repassword)]]> </param> <message>两次密码必须一致</message> </field-validator> </field> <!--对age属性进行验证--> <field name="users.age"> <field-validator type="int"> <param name="min">0</param> <param name="max">150</param> <message>年龄不合法</message> </field-validator> </field> <!--对邮箱属性进行验证--> <field name="users.email"> <field-validator type="email"> <message>邮箱格式不正确</message> </field-validator> </field> <!--对手机号码进行验证--> <field name="users.phonenumber"> <field-validator type="regex"> <param name="regex"> <![CDATA[ ^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8})|(0\d{2}-\d{7,8})|(0\d{3}-\d{7,8})$ ]]> </param> <message>手机号码格式错误</message> </field-validator> </field> </validators>