我目前正在尝试学习Struts2。
我创建了一个表单,一个处理它的动作,一个用于验证它的XML以及struts.xml中的动作。
每次显示表单(即使是第一次),Struts2都会尝试进行验证,因此在用户有机会完成表单之前就显示错误。
以下是相关代码:
<!-- /WebContent/views/user/login.jsp --> <?xml version="1.0" encoding="ISO-8859-1" ?> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Page</title> <s:head /> </head> <body> <h1>Login Page</h1> <s:form action="executeUser"> <s:textfield key="userBean.userName" /> <s:password key="userBean.password" /> <s:submit align="center" /> </s:form> </body> </html>
<!-- /src/struts.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="overviewofstruts" extends="struts-default"> <action name="loginUser" class="hu.flux.user.LoginUserAction" method="execute"> <result name="input">/views/user/login.jsp</result> </action> <action name="executeUser" class="hu.flux.user.LoginUserAction" method="execute"> <result name="input">/views/user/login.jsp</result> <result name="success">/views/user/login_thankyou.jsp</result> </action> </package> </struts>
// /src/hu/flux/user/LoginUserAction.java package hu.flux.user; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginUserAction extends ActionSupport { private User userBean; public void setUserBean(User userBean) { this.userBean = userBean; } public User getUserBean() { return userBean; } public String login() throws Exception { return this.execute(); } public String execute() throws Exception { return SUCCESS; } public String input() throws Exception { return INPUT; } }
<!-- // /src/hu/flux/user/LoginUserAction-validation.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <validator type="requiredstring"> <param name="fieldname">userBean.userName</param> <message>Username is required.</message> </validator> <validator type="requiredstring"> <param name="fieldname">userBean.password</param> <message>Password is required.</message> </validator>
我需要做些什么或改变一下,以使支撑架首次显示该表格而不会抱怨所有空白字段?
是的,我知道这个问题。通常,我正在使用以下解决方法。
标记execute为org.apache.struts2.interceptor.validation.SkipValidation
execute
org.apache.struts2.interceptor.validation.SkipValidation
@SkipValidation public String execute() throws Exception { return SUCCESS; }
因此,第一遍将忽略验证方法。但是 输入 将被验证。