最近在学习使用struts2开发web项目。从开始的struts的配置到之后的各种功能的尝试都遇到了很多问题,在网上找了一下,比较普遍的是使用struts2.1或更早版本的经验,但是struts2版本已经更新到struts2.3.16.1,很多之前的经验已经不再适用,这还是比较令人抓狂的事情。所以打算把我开发中遇到的问题以及解决方法记下来,提醒自己的同时希望能帮助到后来的同学。这一篇介绍的内容是struts2的Ajax校验的配置及相关内容,该方法对struts2.1之后版本均适用。
struts2.1之后把Ajax主题模板放在了struts2-dojo-plugin.jar中。首先把dojo插件包放在项目lib文件夹下,并且build path即可。
jsp中代码要注意的是:
1、<sx:head/>必须设置,否则无法生成Dojo的Ajax方法
2、<s:form/>标签中的应validate设置为false,否则会先进行客户端校验(默认不设置就是false)。
3、最最重要的是,为了执行ajax校验,<sx:submit/>标签中的validate必须设置为true。网上很多帖子都忽略了这一点。
jsp代码:
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax validation</title>
<sx:head/>
</head>
<body>
<center>
<div>
<s:form action="registerAction" method="post">
<s:textfield label="username" name="userName"></s:textfield>
<s:textfield label="password" name="password"></s:textfield>
<s:textfield label="age" name="age"></s:textfield>
<sx:submit value="submit" validate="true"></sx:submit>
</s:form>
</div>
</center>
</body>
</html>
RegisterAction代码(这里仅实现几个简单的校验功能)
package action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private static final long serialVersionUID = 6211175821803063158L;
private String userName;
private String password;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void validate(){
if("xiaoqi".equals(userName)){
addFieldError("username","username is existed");
}
if("".equals(password)){
addFieldError("password","password can not be null");
}
}
}
struts.xml配置跟配置一般action一样
<?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="testAjax" extends="struts-default">
<action name="registerAction" class="action.RegisterAction">
<result name="input">/register.jsp</result>
</action>
</package>
</struts>