我是Struts2的新手,我想在同一页面上验证两个表单标签:
userId
行动password
和Login
个字段
现在我的问题是当我将addfielderror()
应用于登录即(username
和password
字段)并填写注册表单时,新用户将没有userId
和password
登录。它显示登录表单标记的错误,该标记当时为空白。这种行为是错误的,反之亦然。所以,我该怎么做,当我正在登录时,它应该只检查登录操作,当我注册时应检查注册操作?
这是我Login
行动的代码:
<s:form method="Post" action="Login">
<s:textfield type="text" class=" input-small span2" name="login.Email" placeholder="Email"></<s:textfield >
<s:password type="password" class=" input-small span2" name="login.Pass" placeholder="Password"></ s:password>
<button type="submit" class="btn">Sign in</button> <br />
</s:form>
这是注册码:
<s:form method="POST" action="Registor">
<s:textfield class="span1" id="fname" name="FirstName" placeholder="First Name"></s:textfield>
<s:textfield class="span1" id="Lname" name="LastName" placeholder="Last Name"></s:textfield>
<s:password class="span2" id="password" placeholder="Password" name="Password"></s:password><br />
<s:textfield class="span2" id="email" placeholder="Email ID" name="Email_Id"></s:textfield>
<br />
<s:select headerKey="1" id="gender" headerValue="Select Gender" list="#@java.util.HashMap@{'Male':'Male','Female':'Female'}" name="Gender"></s:select><br />
<button type="submit" id="submit" >Submit</button><br />
</s:form>
验证码
public void validate() {
//This is for login action
if((login.getPassword().equals("foobar")){
addActionMessage(SUCCESS);
}else{
addFieldError("Password", "Password should be greater then 6");
}
//This is for registration action
if((user.getPassword() == null) || (user.getPassword().length() < 6)){
addFieldError("Password", "Password should be greater then 6");
}
}
现在,当我输入正确的密码时,"foobar"
会在注册表单上显示错误
"Password should be greater then 6"
它应该显示登录操作的登录成功消息。
Struts.xml
<package name="default" extends="struts-default" >
<action name="Login" class="org.register.customers.RegisterUserAction" method="getLogin">
<result name="input">index.jsp</result>
<result name="success">UserLoging.jsp</result>
<result name="error">error.jsp</result>
</action>
<action name="Registor" class="org.register.customers.RegisterUserAction" method="getRegistor">
<result name="input">index.jsp</result>
<result name="success">RegistorSuccess.jsp</result>
<result name="error">index.jsp</result>
</action>
</package>
答案 0 :(得分:1)
据我所知,您希望将两个不同操作的验证逻辑分开但您只有一个方法validate
,并且两个操作映射到同一个操作类的方法。除了执行编程验证之外,您还应该使用验证拦截器来执行与执行操作相对应的validate
方法的前缀方法调用。假设您的动作类扩展ActionSupport
,因此您不必实现validate()
方法也不必覆盖它。然后单独编写代码
public void validateLogin() {
//This is for login action
if(login == null) {
addActionError("Login is null");
} else
if("foobar".equals(login.getPassword()){
addActionMessage(SUCCESS);
} else {
addFieldError("Password", "Password should be greater then 6");
}
}
public void validateRegister() {
//This is for registration action
if(user == null) {
addActionError("User is null");
} else
if(user.getPassword() == null || user.getPassword().length() < 6) {
addFieldError("Password", "Password should be greater then 6");
}
}