首页 > 代码库 > struts2校验器

struts2校验器

一、struts.xml

<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="http://www.mamicode.com/true" />
    <constant name="struts.devMode" value="http://www.mamicode.com/true" />
    <constant name="struts.action.extension" value="http://www.mamicode.com/shtml"/>
    <package name="default" namespace="/sys" extends="struts-default">
        <!-- 全局变量 -->
    	<global-results>
    		<result name="login">/page/login.jsp</result>
    	</global-results>
    	<action name="user_*" class="com.lovo.u34.action.LoginAction" method="{1}">
    		<result name="ok">/page/ok.jsp</result>
    		<!-- 验证失败,跳本来这个jsp -->
    		<result name="input">/page/{1}.jsp</result>
    	</action>
    </package>
</struts>

二、jsp

....index.jsp

<h1><a href="http://www.mamicode.com/page/login.jsp">点击我》》》登录</a></h1>

....login.jsp

<body>
	<h1>欢迎来到登录界面</h1><br/>
	<form action="sys/user_login.shtml">
	<!-- 校验用户名 -->
	<s:fielderror cssStyle="color:red;" fieldName="name"></s:fielderror>
		用户名:<input type="text" name="name"/><br/>
	<!-- 校验密码 -->
	<s:fielderror cssStyle="color:red;" fieldName="password"></s:fielderror>
		密    码:<input type="password" name="password"/><br/>
		<input type="submit" value="http://www.mamicode.com/登录"/>
	</form>
</body>

....ok.jsp

<body>
	<h1>登录成功!!!</h1>
</body>

三、Action

public class LoginAction extends BaseAction implements ModelDriven<User>{
	public User user= new User();
	public String login(){
		if("zhangsan".equals(user.getName())&&"pwd123".equals(user.getPassword())){
			user.setPassword("");
			sessionMap.put("user", user);//session里面不存密码,其他都有,数据库中不变
			return "ok";
		}else{
			return INPUT;
		}
	}
	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return user;
	}
}

四、校验器

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator 1.0.2//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>

	 <field name="name">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>警告:账号不能为空!</message>
        </field-validator>   
        <field-validator type="stringlength">
            <param name="minLength">4</param>
            <param name="maxLength">10</param>
            <param name="trim">true</param>
            <message key="字符串的长度在4-10之间,请确认无误后登录"></message>
        </field-validator>
    </field>
    
    <field name="password">
    	<field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>警告:密码不能为空!</message>
        </field-validator>   
    
    	<field-validator type="stringlength">
            <param name="minLength">4</param>
            <param name="maxLength">10</param>
            <param name="trim">true</param>
            <message key="字符串的长度在4-10之间,请确认无误后登录"></message>
        </field-validator>
    </field>
</validators>

  

  

  

  

  

  

struts2校验器