Struts2框架中为什么要继承ActionSupport类,以及实现过程

阵营风云

struts可以继承ActionSupport类,也可以不继承,继承的好处简单来说就是更方便实现验证,国际化等功能,与struts2的功能结合紧密,方便我们开发。

ActionSupport类的作用:

此类实现了很多实用的接口,提供了很多默认的方法,这些默认方法包括国际化信息,默认的处理用户请求的方法等,可以大大简化action的开发,在继承ActionSupport的情况下,必须有无参构造函数。

下面用在struts2框架搭建完成的基础上,用 用户请求的例子来实现ActionSupport类:

1.创建视图层两个页面index.jsp和welcome.jsp页面,下面只展示index.jsp页面,welcome.jsp页面的代码自己简单写一下看一下效果就行。这个jsp页面的标签会在相应的字段处输出错误信息。

<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%>

<%@ taglib prefix="s" uri="/struts-tags"%>

Insert title here


账号:


密码:

2.实现action类封装HTTP请求参数,类里面应该包含与请求参数对应的属性,并为属性提供get,set方法,再说一次,在继承ActionSupport的情况下,必须有无参构造函数。

validate方法内部,对请求传递过来的数据进行校验,而且我们也能看出来同一个数据可以进行多方面的验证,如果不满足要求,内容将会在页面上直接显示。里面重写了 execute() throws Exception方法,返回字符串。

package com.hnpi.action;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{

private String account;

private String password;

private String submitFlag;

public String execute() throws Exception {

this.businessExecute();

return "toWelcome";

}

public void validate(){

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() {

return account;

}

public void setAccount(String account) {

this.account = account;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getSubmitFlag() {

return submitFlag;

}

public void setSubmitFlag(String submitFlag) {

this.submitFlag = submitFlag;

}

}

3.从上面我们也可以看出来,validate方法是没有返回值的,如果验证不成功的话,错误信息该怎么在页面上显示出来呢?我们需要在struts.xml中的Action配置里面,添加一个名称为input的result配置,没有通过验证,那么会自动跳转回到该action中名称为input的result所配置的页面。

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

/welcome.jsp

/index.jsp

下面我们来看一下代码效果图:

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

电动车后面换个碟刹多少钱
瘦瘦錠減肥有用嗎?藥師親揭自身經驗:3個月瘦15公斤