1. 程式人生 > >struts2中手動完成輸入校驗

struts2中手動完成輸入校驗

手動校驗是通過重寫validate()方法來實現的

以登入為例:

1.Login.jsp程式碼

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Login</title>
</head>
<body>
    <s:form action="Login.action">
        <s:textfield name="name" label="Name"/>
        <s:fielderror>
            <s:param>name.xml</s:param>
        </s:fielderror>
        <s:password name="password" label="Password"/>
        <s:fielderror>
            <s:param>password.xml</s:param>
        </s:fielderror>
        <s:submit value="Login"/>
    </s:form>
</body>
</html>

2.Login.java程式碼

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {
private String name;
private String password;
private String message;

public String execute(){
message = "Welcome, xml!";
return SUCCESS;
}

public void validate(){       //這裡必須為validate()方法
if(!name.equalsIgnoreCase("xml")){
this.addFieldError("name.xml", "使用者名稱必須為xml");
this.addActionError("使用者名稱錯誤,登入失敗");
}
if(!password.equalsIgnoreCase("xml")){
this.addFieldError("password.xml", "密碼必須為xml");
this.addActionError("密碼錯誤,登入失敗");
}
}
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;
}


public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

3.struts.xml檔案中進行關聯

 <action name="Login" class="com.koubei.Login">
            <result name="success">/Welcome.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>

4.登入成功頁面

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>welcome</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

這裡驗證validate()方法是自動呼叫的