Struts2.3 Ajax校验配置

本文介绍如何在Struts2.1及以后版本中配置并实现Ajax校验功能,包括必要的配置步骤、JSP页面编写技巧及Action验证逻辑。

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

最近在学习使用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>  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值