使用Struts的自定义Validate

Validating.java

package practice.structs2;

import com.opensymphony.xwork2.ActionSupport;

public class Validating extends ActionSupport
{
    private String username;
    private String password;
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getUsername()
    {
        return this.username;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }
    public String getPassword()
    {
        return this.password;
    }
    public String execute()throws Exception
    {
        if(getUsername().equals("hello") && getPassword().equals("kitty"))
        {
            return "success";
        }
        else
        {
            return "error";
        }
    }
    public void validate()
    {
        if(null == getUsername()|| getUsername().trim().equals(""))
        {
            addFieldError("username","请输入用户名!");
        }
        if(null == getPassword() || getPassword().trim().equals(""))
        {
            addFieldError("password","请输入密码!");
        }
    }
}

 

struts.xml配置

这里必须填写一个input因为Validate默认使用input作为返回result

<action name="Validating" class="practice.structs2.Validating">
            <result name="input">/Validate.jsp</result>
            <result name="error" >/Validate.jsp</result>
            <result name="success" >/showBook2.jsp</result>
</action>

 

Validate.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'Validate.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  <body>
    <s:form action="Validating.action" >
        <s:label value="系统登录" ></s:label>
        <s:textfield name="username" label="用户名" >
        </s:textfield>
        <s:password name="password" label="密码" >
        </s:password>
        <s:submit value="提交" >
        </s:submit>
    </s:form>
  </body>
</html>

posted on 2011-10-12 16:52  冰危节奏  阅读(139)  评论(0)    收藏  举报

导航