struts2.0校验使用

一:创建action
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;
        }
    }

}


二:编写LoginAction-validation.xml 注:xml的命名格式为类名-validation.xml,放在action同一个包里面
<?xml version="1.0" encoding="GBK" ?> 
  <!DOCTYPE validators (View Source for full doctype...)> 
<validators>
<field name="username">
<field-validator type="requiredstring" short-circuit="false">
  <message key="user.required" /> 
  </field-validator>
  </field>
<field name="password">
<field-validator type="requiredstring" short-circuit="false">
  <message key="pass.required" /> 
  </field-validator>
  </field>
  </validators>

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

你可能感兴趣的:(java,xml)