struts2.0校验使用

一:重写validate
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 (getUsername().equals("scott")
                && getPassword().equals("tiger") )
		{
			ActionContext.getContext().getSession().put("user" , getUsername());
            return SUCCESS;
        }
		else
		{
            return ERROR;
        }
    }


	public void validate()
	{
		if (getUsername() == null || getUsername().trim().equals(""))
		{
			addFieldError("username", getText("user.required"));
		}
		if (getPassword() == null || getPassword().trim().equals(""))
		{
			addFieldError("password", getText("pass.required"));
		}
	}

}

二:页面
<s:form action="Login">
            <s:textfield name="username" key="user"/>
            <s:textfield name="password" key="pass"/>
            <s:submit key="login"/>
</s:form>

你可能感兴趣的:(java)