struts可以继承ActionSupport类,也可以不继承,继承的好处简单来说就是更方便实现验证,国际化等功能,与struts2的功能结合紧密,方便我们开发。
ActionSupport类的作用:
此类实现了很多实用的接口,提供了很多默认的方法,这些默认方法包括国际化信息,默认的处理用户请求的方法等,可以大大简化action的开发,在继承ActionSupport的情况下,必须有无参构造函数。
下面用在struts2框架搭建完成的基础上,用 用户请求的例子来实现ActionSupport类:
1.创建视图层两个页面index.jsp和welcome.jsp页面,下面只展示index.jsp页面,welcome.jsp页面的代码自己简单写一下看一下效果就行。这个jsp页面的<s:fielderror/>标签会在相应的字段处输出错误信息。
<%@ page language="java" contentType="text/html; charset=utf-8" <%@ taglib prefix="s" uri="/struts-tags"%> <meta http-equiv="Content-Type" content="text/html; utf-8"> <title>Insert title here</title> <form action="helloworldAction" method="post"> <input type="hidden" name="submitFlag" value="login"/> <font color=red><s:fielderror fieldName="account"/></font> 账号:<input type="text" name="account"> <font color=red><s:fielderror fieldName="password"/></font> 密码:<input type="password" name="password"> <input type="submit" value="提交">
2.实现action类封装HTTP请求参数,类里面应该包含与请求参数对应的属性,并为属性提供get,set方法,再说一次,在继承ActionSupport的情况下,必须有无参构造函数。
validate方法内部,对请求传递过来的数据进行校验,而且我们也能看出来同一个数据可以进行多方面的验证,如果不满足要求,内容将会在页面上直接显示。里面重写了 execute() throws Exception方法,返回字符串。
import com.opensymphony.xwork2.ActionSupport; public class RegisterAction extends ActionSupport{ private String submitFlag; public String execute() throws Exception { if(account==null || account.trim().length()==0){ this.addFieldError("account", "账号不可以为空"); if(password==null || password.trim().length()==0){ this.addFieldError("password", "密码不可以为空"); if(password!=null && !"".equals(password.trim()) && password.trim().length()<6){ this.addFieldError("password", "密码长度至少为6位"); public void businessExecute(){ System.out.println("用户输入的参数为==="+"account="+account+",password="+password+",submitFlag="+submitFlag); public String getAccount() { public void setAccount(String account) { public String getPassword() { public void setPassword(String password) { this.password = password; public String getSubmitFlag() { public void setSubmitFlag(String submitFlag) { this.submitFlag = submitFlag;
3.从上面我们也可以看出来,validate方法是没有返回值的,如果验证不成功的话,错误信息该怎么在页面上显示出来呢?我们需要在struts.xml中的Action配置里面,添加一个名称为input的result配置,没有通过验证,那么会自动跳转回到该action中名称为input的result所配置的页面。
<?xml version="1.0" encoding="UTF-8"?> "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts./dtds/struts-2.0.dtd"> <package name="helloworld" extends="struts-default"> <action name="helloworldAction" class="com.hnpi.action.RegisterAction"> <result name="toWelcome">/welcome.jsp</result> <result name="input">/index.jsp</result>
下面我们来看一下代码效果图:

这个例子可以看出来,validate方法会先于execute方法被执行,只有validate方法执行后,又没有发现验证错误的时候,才会运行execute方法,否则会自动跳转到你所配置的input所对应的页面。
|