struts2数据校验问题-服务器端数据验证

一,编写一个jsp页面:

代码如下:datatest.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>数据校验</title>
</head>
<body>
<b>你喜欢什么颜色?please answer the question</b>
提示:如果的validate属性值如果设置为true,则action属性中给出的action名称要加上“.action” 不然会报错  
<s:form method="post" theme="xhtml" action="question.action" validate="true">
<s:textfield name="name" label="姓名"/>
<s:textfield name="age" label="年龄"/>
<s:textfield name="answer" label="回答"/>
<s:submit value="提交"/>
</s:form>
</body>
</html>

二、在struts.xml中加入action:

 
        <action name="question" class="action.Question">
        <result name="success">/success.jsp</result>
        <result name="input">/datatest.jsp</result>


三、编写Qeustion.java类,在action包下

package action;

import com.opensymphony.xwork2.ActionSupport;

public class Question extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String name;//姓名
	int age;//年龄
	String answer;//回答
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAnswer() {
		return answer;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}
	

}

四、在同一包下编写一个Question-validator.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN"   
  "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
	<field name="name">
		<field-validator type="requiredstring">
		<message>必须输入姓名</message>
		</field-validator>
	</field>
	<field name="age">
		<field-validator type="int">
		<param name="min">18</param>
		<param name="max">50</param>
		<message>年龄只能是18-50之间</message>
		</field-validator>
	</field>	
</validators>

以上为采取服务端数据校验的方法

运行效果图:

struts2数据校验问题-服务器端数据验证_第1张图片

你可能感兴趣的:(xml,struts,服务器端校验)