如何在struts2中 对指定Action的方法进行框架(xml)校验?

问题描述: 1. 保存在线咨询功能
2. Action的保存方法是 addConsult()
3. 进行struts2的框架校验 校验规则配置在 WebConsultManagerAction-validation.xml
4. 要求校验规则只对 addConsult() 方法进行有效

WebConsultManagerAction 类如下:

[code="java"]package com.teamax.web.struts.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;
import com.teamax.web.service.WebConsultService;
import com.teamax.web.struts.actionForm.WebConsultForm;
import com.teamax.web.util.IPUtils;

/**

  • @author 作者:qiuzq
  • E-mail:qzq_hello@163.com
  • @version
  • 创建时间:Mar 23, 2009 4:05:30 PM
  • 类说明: 在线咨询
  • 修改记录:
    */
    public class WebConsultManagerAction extends ActionSupport implements ServletRequestAware{

    private static final long serialVersionUID = -8789596114574032277L;
    private static final WebConsultService webConsultService = new WebConsultService();
    private WebConsultForm webConsultForm = new WebConsultForm();
    private HttpServletRequest request;

    public void setServletRequest(HttpServletRequest request) {
    this.request = request;

    }

    public WebConsultForm getWebConsultForm() {
    return webConsultForm;
    }

    public void setWebConsultForm(WebConsultForm webConsultForm) {
    this.webConsultForm = webConsultForm;
    }

    //增加在线咨询
    public String addConsult() {

    webConsultForm.setUserip(IPUtils.getIpAddr(this.request));
    webConsultService.addConsult(webConsultForm);
    
    return SUCCESS;
    

    }

}[/code]

WebConsultManagerAction-validation.xml 校验规则如下:

[code="java"]<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<field name="webConsultForm.title">
   <field-validator type="requiredstring">
       <param name="trim">true</param>
       <message key="consultForm.title" />
   </field-validator>
</field>

<field name="webConsultForm.usercontent">
   <field-validator type="requiredstring">
       <param name="trim">true</param>
       <message key="consultForm.usercontent" />
   </field-validator>
</field>

<field name="webConsultForm.ccode">
   <field-validator type="requiredstring">
       <param name="trim">true</param>
       <message key="consultForm.ccode" />
   </field-validator>
</field>

[/code]

我知道你的Action中有很多方法,你不想每一个方法都使用这一个校验

你可以

在xxxAction中配置多个校验逻辑
(1)xxxAction中一个校验方法public String abc()throws Exception{}
(2)struts.xml中为该action设置method="abc"
(3)校验XML命名:xxxAction-abc-validation.xml
(4)注:在这种情况下,xxxAction-validation.xml依然会校验,所以我们称其为全局的Action校验
(5)建议:若一个Action中处理多个业务逻辑,不写xxxAction-validation.xml,为每个业务逻辑写一个校验xml,防止校验之间的相互干扰

http://tech.it168.com/j/2007-09-23/200709230947419.shtml
很简单,请参考

http://www.blogjava.net/max/archive/2006/11/14/81106.html
这个更加详细