ActionSupport是Struts2框架提供的一个便利类,为最常见的操作提供默认实现,继承它后可以做很多操作,例如国际化,验证,等等.
ActionSupport是Action下延伸出来的类,它是Action的子类,Actionsupport这个工具类在实现了Action接口的基础上还定义了一个validate()方法,重写该方法,它会在execute()方法之前执行,如校验失败,会转入input处,必须在配置该Action时配置input属性。
下面在上一篇博客展示的基础上继续完成代码示例:
首先是视图层页面:register.jsp 另一个简略
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; utf-8">
<title>Insert title here</title>
<style type="text/css">
ul,li {
list-style-type:none;
margin:0px;
float:left;
}
</style>
</head>
<body>
<form action="helloworldAction" method="post">
<input type="hidden" name="submitFlag" value="login"/>
<div>
<font color=red><s:fielderror fieldName="account"/></font>
<br/>
账号:<input type="text" name="account">
</div>
<div>
<font color=red><s:fielderror fieldName="password"/></font>
<br/>
密码:<input type="password" name="password">
</div>
<input type="submit" value="提交">
</form>
</body>
</html>
接着,
是在Action中用其中的validate()方法进行校验,如下例:
package com.hnpi.action;
import com.opensymphony.xwork2.ActionSupport;
public class strutsAction 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;
}
}
接上,配置struts.xml。添加名称为input的result配置,没通过验证则自动跳转到该action中名为input的result所配置的页面。
<?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>
<package name="helloworld" extends="struts-default">
<action name="helloworldAction" class="com.hnpi.action.strutsAction">
<result name="toWelcome">/welcome.jsp</result>
<result name="input">/register.jsp</result>
</action>
</package>
</struts>
大体完毕。