在表单提交的时候,经常需要对用户名或者密码为空的情况进行验证,有时候可能时候JavaScript,当然也不排除
使用Struts2。其实,Struts2提供了非常强大的表单验证功能,下面我们来演示一下最简单的表单验证。
同样,在Struts2中,表单提交的值通过params拦截器进行动态的存入到了相对应的Bean的属性中去,我们同样可
以构建一个Bean然后让struts2去加载实例化他,然后自动的将我们需要的Bean的属性注入到其中去,这样可以减少很
多的代码量。
首先是Action代码
package com.bird.chapterTwo; import com.bird.chapterTwo.bean.User; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport{ private static final long serialVersionUID = 1L; private static final String GREETING = "Hello"; @Override public void validate() { if(getUser().getUsername().length()==0){ addFieldError("user.username", getText("请输入用户名")); } if(getUser().getPassword().length()==0){ addFieldError("user.password", getText("请输入密码")); } } @Override public String execute() throws Exception { user.setUsername(user.getUsername()+GREETING); return SUCCESS; } private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
<?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.i18n.encoding" value="UTF-8"></constant> <constant name="struts.devMode" value="false" /> <package name="chapterTwo" namespace="/chapterTwo" extends="struts-default"> <action name="Name"> <result>/NameCollector.jsp</result> </action> <action name="HelloWorld" class="com.bird.chapterTwo.HelloWorld"> <result name="success">/chapterTwo/HelloWorld.jsp</result> <result name="input">/NameCollector.jsp</result> </action> </package> </struts>一定要注意那个name="input",这个就是表单验证失败的时候转向的页面,我们这里让他转向了输入的界面。
然后是输入界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Name Collector</title> </head> <body> <h4>Enter Your Name</h4> <s:form action="HelloWorld"> <s:textfield name="user.username" label="Your Name"></s:textfield> <s:textfield name="user.password" label="Your Password"></s:textfield> <s:submit/> </s:form> </body> </html>
后注入这个属性了。
最后是显示界面,同样的方法,
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>HelloWorld</title> </head> <body> <h3>Custom Greeting page</h3> <h4><s:property value="user.username"></s:property></h4> </body> </html>