利用手工编码的方式对srtus2进行输入验证

action方法进行校验有两种方法一种是:

1手工编码书写

2一种是用xml

输入校验的流程:

1类型转化器对请求参数执行类型转化,并把转换后的值赋给action属性。

2.如果执行类型转化的过程中出现异常,系统会把异常信息保存到actioncontextconversionerror拦截器会将信息添加到fileerroes里。不管类型转化是否出现异常,都会进入第3步骤。

3系统通过反射技术先调用actionvalidateXxx()方法,Xxx是特定的方法名字。

4z再调用action,如果有错误信息就会将错误信息返回到input视图上面。

 

下面来写一个实例用手工编码的方法:

写有一个from表单的index.JSPhead加上

<%@taglib  uri="/struts-tags"  prefix="fish"%>//通过引入struts标签库

body

<fish:fielderror></fish:fielderror>//会显错误信息用的

    <form action="/struts2test8/test/redfishmyMehod2.action" method="get">

        <a>用户名:</a><input type="text" name="username"><br><a>手机号:</a><input

            type="text" name="phone"><br><input type="submit"

            value="提交">

    </form>

 

 

接着我们写struts.Xml

<package name="fish" namespace="/test" extends="struts-default" >

<action name="redfish*" class="com.fish.Test" method="{1}">

<result name="success">/ok.jsp</result>

<result name="input">/index.jsp</result>//如果有错误信息将会送给inout的视图。那么就不在执行success的视图。

</action>

</package>

接着写一个关于写一个类型转化器来验证。

package com.fish;

 

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionSupport;

 

publicclass Test  extends ActionSupport{//首先得继承这个类

String username;//这个属性和jsp、里面的name是一样的,

String phone;

public String getUsername() {

    returnusername;

}

publicvoid setUsername(String username) {

    this.username = username;

}

public String getPhone() {

    returnphone;

}

publicvoid setPhone(String phone) {

    this.phone = phone;

}

 

public String myMehod1(){

    ActionContext.getContext().put("message", "保存成功!");

    return"success";

}

public String myMehod2(){

    ActionContext.getContext().put("message", "更新成功!");

    return"success";

}

@Override

publicvoid validate() {//要想验证必需重写这个方法。但是这样是可以验证myMehod1myMehod2的方法。也就是对action的所有方法进行校验,所以要想对特定方法进行校验的时候我们只要遵循一个格式. validateXxx()方法这样我们就可以将只验证特定方法,比如我只想验证myMehod2方法,我们就可以这么写validateMyMehod2()格式是固定的。

    if(username==null||"".equals(username.trim())){

        addFieldError("username", "用户名不能为空");

    }

    if(phone==null||"".equals(phone.trim())){

        addFieldError("phone", "手机号不能为空");

    }else{

        if(!Pattern.compile("^1[358]\d{9}$").matcher(phone).matches()){

            addFieldError("phone", "手机格式不正确");

        }

    }

   

    super.validate();

}

 

 

}

 

原文地址:https://www.cnblogs.com/dyllove98/p/3190323.html