`

struts2表单级验证

阅读更多

   struts2表单级验证,以最简单的登陆页面的用户名密码为例。

(1)新建login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>    
<!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=ISO-8859-1">
<title>登陆(采用struts2标签)</title>
</head>
<body>
   <s:form action="login" method="post">
      <s:textfield name="userName" label="userName" />
      <s:textfield name="password" label="password" />
      <s:submit label="submit"/>
   </s:form>
</body>
</html>

 

注:采用struts2标签,在页面头部加入<%@ taglib uri="/struts-tags" prefix="s"%> 

 

(2)loginAction中

package login;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
    private String userName = "";
    private String password = "";
	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 String execute() throws Exception{
		if(this.userName==null || !"wu".equals(this.userName) || this.password==null || !"1".equals(this.password)){
		    this.addFieldError("userName", "userName or password error");
			return "failure";	
		}
		return "success";
	}
	/**
	 * 表单级验证
	 */
	public void validate(){
		if(this.userName==null || "".equals(this.userName)){
			this.addFieldError("userName", "userName is required");
		}
		if(this.password==null || "".equals(this.password)){
			this.addFieldError("password", "password is required");
		}
	}
    
}

该类继承了ActionSupport父类。复写其中的validate()方法。

 

(3)struts.xml

<?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="login" extends="struts-default">
          <action name="login"  class="login.LoginAction">
            <result name="success" >/loginSuccess.jsp</result>
            <result name="input" >/login.jsp</result>
            <result name="failure" >/login.jsp</result>
          </action>
       </package>

    </struts>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics