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沒有任何區別
[java]
- 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放置在同一個目錄下)
[html]
- <?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>