[Struts2学习笔记] -- 输入校验

Struts2可以对客户端的输入进行校验,通过重写ActionSupport的validate方法来实现,具体如下:

首先通过用struts标签库创建一个form表单,表单中控件的name与action中的域名称相同,接着在validate方法中编写验证代码,若验证失败则会自动返回input。代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>My JSP 'index.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
      <s:actionerror/>
    <s:form action="signIn">
        <s:textfield label="UserName" name="username"></s:textfield>
        <s:textfield label="PassWord" name="password"></s:textfield>
        <s:textfield label="age" name="age"></s:textfield>
        <s:submit>Sign in</s:submit>
    </s:form>
  </body>
</html>
form表单代码
package cn.net.bysoft.lesson4;

import com.opensymphony.xwork2.ActionSupport;

public class SignInAction extends ActionSupport {
    
    public String signIn() throws Exception {
        return SUCCESS;
    }
    
    public String signOut() throws Exception {
        return SUCCESS;
    }
    
    public void validateSignIn() {
        if(username.equals("")){
            addFieldError("username", "username invalid");
        }
        if(password.equals("")){
            addFieldError("password", "password invalid");
        }
        if(age < 0 || age >= 150) {
            addActionError("age error");
        }
    }
    
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    private String username;
    private String password;
    private int age;
    private static final long serialVersionUID = 1100577442199735808L;
}
action类代码

在action中,可以将错误信息通过addFieldError方法进行保存,也可以通过addActionError方法保存。

此处有一细节,若在一个action中想编写多个验证方法,可以将执行方法首字母大写后与validate合并起来命名验证方法,如signIn()处理方法的验证方法为validateSignIn()。execute的验证方法为validateExecute()。

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.custom.i18n.resources" value="message"></constant>

    <package name="struts2_3_24_1" extends="struts-default">
        <action name="helloWorld" class="cn.net.bysoft.lesson1.HelloWorldAction">
            <result>lesson1/hello.jsp</result>
        </action>
        <action name="login" class="cn.net.bysoft.lesson2.LoginAction">
            <result name="success">/lesson2/success.jsp</result>
            <result name="input">/lesson2/login.jsp</result>
        </action>
        <action name="point" class="cn.net.bysoft.lesson3.PointAction">
            <result name="success">/lesson3/output.jsp</result>
            <result name="input">/lesson3/index.jsp</result>
        </action>
        <action name="signIn" class="cn.net.bysoft.lesson4.SignInAction" method="signIn">
            <result name="success">/lesson4/output.jsp</result>
            <result name="input">/lesson4/index.jsp</result>
        </action>
        <action name="signOut" class="cn.net.bysoft.lesson4.SignInAction" method="signOut">
            <result name="success">/lesson4/ok.jsp</result>
            <result name="input">/lesson4/output.jsp</result>
        </action>
    </package>
</struts>
struts的配置文件代码

另外,类型转换错误的异常信息由struts定了,比如页面年龄输入一个a,但是age是int类型,则会引发类型转换异常Invalid field value for field "age".若角色这个提示不合适,可以自定义类型转换异常,有两种方式:

第一种是定义一个全局的属性文件,比如在src中定义一个message.properties,并在struts的配置文件中配置进入。<constant name="struts.custom.i18n.resources" value="message"></constant>

xwork.default.invalid.fieldvalue={0} convert error!

{0}位置是我们的报错属性名称。

第二种是定义一个局部的属性文件,在创建action的包下创建一个同名的属性文件,比如在cn.net.bysoft.lesson4包下创建一个SignInAction.properties文件,不需要在struts配置文件中配置。

invalid.fieldvalue.age=u5E74u9F84u7C7Bu578Bu8F6Cu6362u9519u8BEF

在属性文件中无法使用汉字,可以使用native2ascii工具把汉字转换成Unicode字符。
最终运行结果如下:

输入空的姓名和密码,并配输入超过200岁的年龄,可以看到姓名和密码的错误被放到了addFieldError中,而年龄的验证被放到了addActionError中。

在输入一个类型转换错误的年龄,可以看到类型转换错误被struts自动放到了addFieldError中,并且通过我们的属性文件替换成了中文的错误信息。

最后输入正确的信息则可以提交通过。

原文地址:https://www.cnblogs.com/DeadGardens/p/5231990.html