国内vps要在Java中使用Struts2进行表单验证,可以按照以下步骤进行操作:
<action name="login" class="com.example.LoginAction"> <result name="input">/login.jsp</result> <result>/success.jsp</result> <interceptor-ref name="defaultStack"> <param name="validation.excludeMethods">execute</param> </interceptor-ref> <interceptor-ref name="validation"> <param name="excludeMethods">input</param> </interceptor-ref> <interceptor-ref name="workflow"> <param name="excludeMethods">input</param> </interceptor-ref> </action>
public class LoginAction extends ActionSupport { private String username; private String password; public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } @Override public void validate() { if (username == null || username.trim().equals("")) { addFieldError("username", "Username is required"); } if (password == null || password.trim().equals("")) { addFieldError("password", "Password is required"); } } public String execute() { // Login logic return SUCCESS; } }
<s:form action="login" method="post"> <s:textfield name="username" label="Username" /> <s:textfield name="password" label="Password" /> <s:submit value="Login" /> </s:form> <s:fielderror fieldName="username" /> <s:fielderror fieldName="password" />
通过以上步骤,您可以在Java中使用Struts2进行表单验证。当用户提交表单时,Struts2会自动执行验证规则并显示错误消息。