AJAX提交Struts2表单(服务器端validation校验出错提示)
1.目标
在基于Struts2的应用中,利用AJAX方式提交表单实现一个登陆验证Action,将服务器端验证结果展现在页面上
字段错误展示:
action 错误提示
2.技术实现
利用struts2-jquery插件和struts2-json插件实现3.实现步骤
3.1依赖jar包
除了struts2-core-2.2.3.jar包以外,还要下载两个jar包
struts2-jquery-plugin-3.1.0.jar
struts2-json-plugin-2.2.3.jar
3.2编写登陆处理类Action
这个Action和我们普通的Action没有任何区别
package com.crazycoder2010.struts2; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private static final long serialVersionUID = 6627313805146336838L; private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String execute() throws Exception { if(!("Kevin".equals(this.name)&&"111111".equals(this.password))){ this.addActionError("Wrong!"); } return INPUT; } }3.3为登陆程序添加验证文件LoginAction-Validation.xml(和LoginAction放置在同一个目录下)
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
- <validators>
- <field name="name">
- <field-validator type="requiredstring">
- <param name="trim">true</param>
- <message>Name is required.</message>
- </field-validator>
- <field-validator type="stringlength">
- <param name="minLength">2</param>
- <param name="maxLength">60</param>
- <message>Name must be between ${minLength} and ${maxLength} characters long.</message>
- </field-validator>
- </field>
- <field name="password">
- <field-validator type="requiredstring">
- <param name="trim">true</param>
- <message>Password is required.</message>
- </field-validator>
- <field-validator type="stringlength">
- <param name="minLength">2</param>
- <param name="maxLength">60</param>
- <message>Password must be between ${minLength} and ${maxLength} characters long.</message>
- </field-validator>
- </field>
- </validators>
这个Action的配置有些特殊,注意
a.package需要继承自json-default包
b.action的拦截器引用jsonValidationWorkflowStack
c.result的type类型为json
d.配置该action需要转化成json对象的字段includeProperties
- <?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="default" extends="json-default">
- <action name="login" class="com.crazycoder2010.struts2.LoginAction">
- <interceptor-ref name="jsonValidationWorkflowStack"></interceptor-ref>
- <result name="input" type="json">
- <param name="ignoreHierarchy">false</param>
- <param name="includeProperties">actionErrors\[\d+\], fieldErrors\..+$, actionMessages\[\d+\]</param>
- </result>
- </action>
- </package>
- </struts>
a.将struts2-jquery的taglib引入页面中
b.在<head>元素中通过<sj:head/>标签引入jquery的css和js文件(这些文件都压缩在struts2-jquery-plugins.jar包中,因此不需要单独下载jquery相关的js了)
c.提交submit按钮改用struts2-jquery插件中的
<sj:submit onCompleteTopics="complete" --在服务器端处理完毕将结果返回到页面时所触发的javascript函数
targets="result" --用来展示结果的容器ID列表,以','分割
onBeforeTopics='clearError' --在将数据提交到服务器端以前所触发的javascript函数,如做一些客户端的验证错误提示信息的清除
返回json结果字符串示例:
{"actionErrors":[],"actionMessages":[],"fieldErrors":{"name":["Name is required."],"password":["Password
is required."]}}
- <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <style type="text/css">
- .errorLabel{color: red;}
- </style>
- <sj:head jquerytheme="cupertino" ajaxcache="false" compressed="false"/>
- </head>
- <body>
- <s:form action="login" method="post" theme="simple" namespace="/">
- <ul id="errorMessages"></ul>
- <p>User Name:</p>
- <p><input name="name"/><span id="error_name"></span></p>
- <p>Password:</p>
- <p><input type="password" name="password"/><span id="error_password"></span></p>
- <sj:submit
- onCompleteTopics="complete"
- targets="result"
- onBeforeTopics="clearError"
- value="Login"/>
- </s:form>
- <script type="text/javascript">
- $.subscribe('clearError', function(event,data) {
- $("#errorMessages").html("");
- $('.errorLabel').html('').removeClass('errorLabel');
- });
- $.subscribe('complete', function(event,data) {
- $("#errorMessages").html("");//先将上次认证的错误消息清除掉
- $('.errorLabel').html('').removeClass('errorLabel');
- var json = $.parseJSON(event.originalEvent.request.responseText);
- if(json.actionErrors && json.actionErrors.length>0){//判断有没有actionErrors
- $.each(json.actionErrors,function(index,data){
- $("#errorMessages").append("<li>"+data+"</li>");
- });
- return;
- }
- if(json.fieldErrors && !isEmpty(json.fieldErrors)){//判断有没有fieldError(LoginAction-validation.xml验证错误)
- $.each(json.fieldErrors,function(index,value){//index就是field的name,value就是该filed对应的错误列表,这里取第一个
- $("#error_"+index).html(value[0]);
- $("#error_"+index).addClass("errorLabel");
- });
- return;
- }
- alert("登陆成功");//既没有actionError有没有fieldError则登陆成功
- });
- function isEmpty(obj){//判断对象是否为空(处理Object obj = {}这种情况认为isEmpty=true)
- for(var p in obj){
- return false;
- }
- return true;
- }
- </script>
- </body>