struts2中手动完成输入校验

来源:互联网 发布:php语言入门 编辑:程序博客网 时间:2024/06/05 08:02

手动校验是通过重写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()方法是自动调用的

原创粉丝点击