对Action指定方法进行校验

本文介绍了一种使用Struts2框架进行输入校验的方法,通过编写特定的验证方法实现对用户提交的数据进行有效性检查。文章详细展示了如何针对不同的Action方法编写对应的验证逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

手工编写代码实现对action指定方法输入校验:

通过validateXxx()方法实现,validateXxx只会校验action中方法名为Xxx的方法。其中Xxx的第一个字母要大写。

code:

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>输入校验</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/person/manage_update.action" method="post">
   		用户名:<input type="text" name="username"><br/>
   		手机号:<input type="text" name="mobile"><br/>
   		<input type="submit" value="提交"/>
   </form>
  </body>
</html>

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/dtds/struts-2.0.dtd">

<struts>
	<package name="person" namespace="/person" extends="struts-default">
	        <action name="manage_*" class="cn.itcast.action.PersonAction" method="{1}">
	        	<result name="input">/index.jsp</result>
	        	<result name="message">/WEB-INF/page/message.jsp</result>
	        </action>
	 </package>
</struts>

Person.action

package cn.itcast.action;

import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PersonAction extends ActionSupport{
	/**
	 * @author wangfeng
	 */
	private static final long serialVersionUID = 6609644196829871636L;
	private String username;
	private String mobile;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	
	public String update(){
		ActionContext.getContext().put("message", "更新成功");
		return "message";
	}
	
	public String save(){
		ActionContext.getContext().put("message", "保存成功");
		return "message";
	}
	
	//will validate the "update" function
	public void validateUpdate(){
		if(this.username==null || "".equals(this.username.trim())){
			this.addFieldError("username", "用户名不能为空");
		}
		if(this.mobile==null || "".equals(this.mobile.trim())){
			this.addFieldError("mobile", "手机号不能为空");
		}else{
			if(!Pattern.compile("^1[358]\\d{9}$").matcher(this.mobile).matches()){
				this.addFieldError("mobile", "手机号格式不正确");
			}
		}
	}

	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值