---
title: "struts学习笔记(二)"
author: "java_hanyu"
date: "2007-10-28T02:19:09Z"
tags: []
slug: "struts"
draft: false
lastmod: "2007-10-28T02:19:09Z"
id: 135979
url: "https://java-hanyu.iteye.com/blog/135979"
---

ActionForm的校验

<struts-config>
  <form-beans>
     <form-bean name="xxx" type="ActionForm的类全名">
     <form-bean name="LoginForm" type="basic.LoginForm">
     <!--配置ActionForm类-->
  </form-beans>
  <action-mappings>
     <action path="/basic/login"  type="alan.struts.basic.LoginAction" 
                 name="xxx" scope="request|sessio(默认值)Form的保存空间">
        <forward name="success" path="/basic/success.jsp"/>
        <forward name="fail" path="/basic/fail.jsp" redirect="false"（重定向，默认false）/>
      </action>
   <action-mappings>
</struts-config>

ActionForm的校验是struts提供的一项类似于Javascript的表单校验的功能。他可以验证用户填写的表单数据的正确性。

ActionForm的校验，如果表单中的数据符不符合规定格式的要求，ActionForm的validate()方法会返回一个ActionError对象，
ActionError对象中封装了一个或多个应用发现的校验错误，每一个错误有一个ActionMessage对象表达，我们可以通
过判断这个ActionError的对象是否为空，如果为空那么表单的数据符合格式要求，不为空就是表单项中就有不符合格式要求的项。

struts标签

在使用struts标签的JSP页面中要先加上以下的标签库的引用
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<bean:message key="errors.username.required">这个标签可以从指定的资源文件中根据指定的key值来取得可以对应的值，
但是需要在struts-config.xml中进行配置。
配置资源，这些资源可以在ActionMessage中使用，也就是在构造ActionMessage是指定资源文件中的key这样，在发现校验
错误时，就可以先在资源文件中指定的key的值了。可以使用struts的<html:errors>
<html:message>、<bean:message>标签都可以显示指定错误的消息。
<struts-config>
    .....
    <message-resources parameter="alan.struts.message.MessageResource" />
    <!--使用message标签时配置资源文件的位置-->
</struts-config>

struts会自动的判断返回ActionError是否为空，如果是空可以自动的转向指定页面，也可以强制不
进行校验，虽然可以在Form中不去覆盖validate()方法，但是那样是不可取的。要实现上面提得到功能还
需要在struts-config中配置。
<action   path="/basic-validate/login"  type="alan.struts.basic.LoginAction"
        		  name="loginValidateForm" scope="request"
        		  validate="true"  input="/basic-validate/login.jsp">
    <!--scope可以指定Form的存放空间，默认为sessoin-->
    <!--action标签中配置validate="false"可以不进行校验，input是指定校验出错跳转的页面-->
    <forward name="success" path="/basic-validate/success.jsp"/>
    <forward name="fail" path="/basic-validate/fail.jsp"/>
</action>

<html:message id="error"><!--id属性是ActionMessage存放在空间中的key-->
  <h1>${error}</h1>
</html:message>
<html:errors>标签只会原样输出在ActionErrors中ActionMessage对应资源文件中对应的值。
<html:messages>标签还可以对输出在ActionError中ActionMessage对应资源文件中对应的值作一些显示效果的修改。
<bean:message key="xxx.xxx">标签只会取资源文件中指定key所对应的值，使用bean:message标签可以实现国际化。


struts的html标签

struts的html标签的使用类似于html标签，但是少有区别，指定类型的方式变成使用不同的标签，这样会绑定struts，
所以旨在需要时使用。
<html:form method="post" action="/basic-validate/login">
<!--
   struts的html标签中的action可以只写转到的actionpath，struts会在解析是自动添加需 要的部分  
-->
	<html:text property="userName" />
	<html:password property="password" redisplay="false"/>
        <!--redisplay="false"不进行回写，只有html:password标签可用-->
        <html:radio property="hibbos">
	<html:submit value="login" />
</html:form>

Struts预定义的Action类

注意：在使用继承Struts预定义的Action类，一定不要覆盖execute方法，否则会导致无法调用自定义Action相应方法。

DispatchAction类(org.apache.struts.actions.DispatchAction)

DispatchAction类是Action类的子类，他提供了有实现的execute方法。

我们写的自定义Action类，可以继承DispatchAction类，但不要覆盖execute方法，可以在自定义类中写反回值和参数表都
与execute方法相同的方法，可以通过在struts-congfig.xml中为这个action的配置中添加一个参数，来判断调哪一个方法，
实际上DispatchAction类就是通过反射机制，通过form中参数调用了自定义Action中的方法，当然这些方法的定义要符合规范，
使用继承DispatchAction类的自定义的Action类，也就会共享同一的Action路径。

注意：使用继承DispatchAction类的自定义的Action，只会匹配一个action路径，只能共享一个ActionForm，如果加上校验，
会产生form表单的参数不一致的情况，会导致校验无法通过。


例：
public class MyAction extends DispatchAction{
	ActionForward add(ActionForm form,HttpServletRequest request,HttpServletResponse response ActionMapping mapping) throws Exception
        {
                    return mapping.findForward("sucess")                     
        }
}

<action path="/add"  type="MyAction" parameter="methodName">
    <!--parameter属性是和form中隐藏域的名字相对应的-->
    <forward name="sucess" path="/sucess.jsp"/>
</action>

<from action="add.do" method="post">
   <input type="hidden" name="methodName" value="add"/>
   <!--
      使用隐藏域为struts传递要调用自定义Action中方法的方法名，是通过与struts-config.xml
      中action标签中的parameter和name属性相对应来获取隐藏域的value。
   -->
   <input type="submit" value="submit"/>
</from>

MappingDispatchAction类(org.apache.struts.actions.MappingDispatchAction)

MappingDispatchAction类是DispatchAction的子类，他和DispatchAction不同点就是可以去匹配多个action路径，这样也就是结决了共用ActoinForm的校验问题了，多个Action的路径使用同一的自定义Action类，这样就不用共享同一个ActionForm，也就不会有校验问题了。


例：
public class MyAction extends MappingDispatchAction{
	ActionForward add(ActionForm form,HttpServletRequest request,HttpServletResponse response ,ActionMapping mapping) throws Exception
        {
                    return mapping.findForward("add")                     
        }
        ActionForward del(ActionForm form,HttpServletRequest request,HttpServletResponse, response ActionMapping mapping) throws Exception
        {
                    return mapping.findForward("del")                     
        }
}

<action path="/add"  type="MyAction" parameter="add">
   <!--parameter属性是指定调用方法的名字-->
   <forward name="add" path="/add.jsp"/>
</action>        
<action path="/del"  type="MyAction" parameter="del">
   <forward name="del" path="/del.jsp"/>
</action>

在JSP页面中也不用在使用隐藏域传递参数，直接在form中的action中就可以直接使用xxx.do匹配了。
<form action="add.do" method="post">
   <input type="submit" value="submit"/>
</form>
<form action="del.do" method="post">
   <input type="submit" value="submit"/>
</form>

LookupDispatchAction(org.apache.struts.actions.LookupDispatchAction)

LookupDispatchAction类也是DispatchAction类的子类，他所实现的功能是解决一个表单多种提交问题的
，他是通过使用资源文件，用submit按钮的value来作为资源文件中的key所对应的值，通过这个值来找到对用的key，在使用这个key来获得指定Map中所对应的值，这个值就是要调用的方法名。

submit的value---->MessageResource.properties中的key----->Map中key对相应的值---->action

例：
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<form method="post" action="${pageContext.request.contextPath}/lookup/adddel.do">
	<input type="submit" value="<bean:message key="button.add" />" name="methodName">
        <!--注意name="methodName"是和strut-config.xml中action标签中的parameter属性-->
	<input type="submit" value="<bean:message key="button.delete" />" name="methodName">
</form>

MessageResource.properties

button.add=add new user
button.delete=delete user

注意：在继承LookupDispatchAction时，要覆盖getKeyMethodMap()方法，并定义Map，向Map中放入指定的键值对。

public class AddDelLookupDispatchAction extends LookupDispatchAction
{
	public Map getKeyMethodMap(){
		Map keyMethodMap= new HashMap();
		keyMethodMap.put("button.add", "add");
		keyMethodMap.put("button.delete", "delete");
		return keyMethodMap;
	}	
    public ActionForward add(ActionMapping mapping,ActionForm form,
                   HttpServletRequest request,HttpServletResponse response) throws Exception
    {    
        return mapping.findForward("add");
    }
    public ActionForward delete(ActionMapping mapping,ActionForm form,
                   HttpServletRequest request,HttpServletResponse response) throws Exception
    {
    	return mapping.findForward("delete");
    }
}

<action   path="/lookup/adddel"  type="alan.struts.actions.AddDelLookupDispatchAction"
        		  parameter="methodName">
            <forward name="add" path="/add.jsp"/>
            <forward name="delete" path="/delete.jsp" />
</action>
<message-resources parameter="alan.struts.message.MessageResource" />

自定义的Action类的一些规则
1，尽量不要在Action类中使用（静态）成员变量，如果使用要加上同步。
2，尽量使各模块间的耦合性降低，最大限度的针对接口编程。
3，可以将共代码方在覆盖父类的方法中，最后可以用super.xxx(xxx)来调用父类的方法，使用父类的实现，并加上了自定义的功能。