---
title: "struts2-rest-plugin 的bug？如果是的话，这个插件的问题可真够多的！"
author: "rustlingwind"
date: "2010-02-23T03:58:49Z"
tags: []
categories: ["企业架构"]
slug: "struts2-rest-plugin-bug"
draft: false
lastmod: "2010-02-24T15:06:26Z"
id: 600453
url: "https://rustlingwind.iteye.com/blog/600453"
---

用注释方式给rest controller 加上拦截器：
@InterceptorRefs({@InterceptorRef("authorization"),@InterceptorRef("defaultStack")})

发现加上拦截器后，立马蹦出来一堆怪问题！

该执行的不执行了：
/userinfos/3.xml
在执行show()之前，
本来该执行 
setId(String id) 方法，但不执行。
本来不应该执行validate()方法，但竟然执行了！

不加拦截器的时候好好的！
晕死了。。。
如果真是struts2-rest-plugin 的bug，可真够过分的！

——本来怀疑是不是拦截器中 invocation.invoke()执行回调时，RestActionInvocation被替换成了DefaultActionInvocation，导致丢掉了rest的特性，但result仍然返回了xml，理应不是。可如果不是这个原因，又是什么原因呢？


==================================================
2010.2.24 这个问题解决了！
==================================================
今天上午忽然发现弄了半天是引用的拦截器栈的名字写错了！
但这个问题背后，其实是我对问题的本质没有理解。刚开始就想到会不会是 actionInvocation 由 restActionInvocation 被替换成了
DefaultActionInvocation所致。但却没往拦截器方面去想。
仔细看了一下 struts2-rest-plugin jar包里的 struts-plugin.xml，里面有个 "restDefaultStack"，我继承人家的"rest-default"package，在引用人家的默认拦截器栈时，当然不应该引用传统的"defaultStack"，而应该引用rest包的"restDefaultStack"，这样id参数自然不会丢失了，validate方法的执行也不会有问题了——show/index都不会执行，update/create 都默认执行。

但是还有个问题。。。


==================================================
2010.2.24 新问题！
==================================================

我想给 controller 中的方法添加拦截器，并且希望拦截器能加在 method 级别上。
看了 convension plugin 的官方文档：
http://struts.apache.org/2.x/docs/convention-plugin.html#ConventionPlugin-Applying@Actionand@Actionsattheclasslevel
所幸文档写的很明确，是支持的！
但是按照文档的样子，照搬到 rest 方式的 controller 上，却有问题！
一段代码：
// PUT /orders/1
    //@Action(interceptorRefs={@InterceptorRef("authorizationStack")})
    @Action(interceptorRefs={@InterceptorRef("authorization"), @InterceptorRef("restDefaultStack")})
    public String update() {
        ordersService.save(model);
        addActionMessage("Order updated successfully");
        return "success";
    }

// GET /orders/1
    public HttpHeaders show() {
        return new DefaultHttpHeaders("show");
    }

    // GET /orders
    public HttpHeaders index() {
        list = ordersService.getAll();
        return new DefaultHttpHeaders("index")
            .disableCaching();
    }

本以为肯定只是拦截 update方法的，但当我访问show或index方法时，拦截器也一样都执行了！
百思不得其解！
所幸又从网上看到了这篇帖子：
http://topic.csdn.net/u/20091214/11/15a63547-92b6-448e-8ddf-143fe3d243f8.html
但该文中提到的是关于convention plugin 方式的，对于rest plugin来说，有其特殊的地方，就是无法给action添加自定义的名字——@Action(value="xxx");

rest方式下，如果要执行controller的update方法，会这样：
PUT /userinfos/{id}.xml
然后会执行对应controller中的update方法。也就是说，rest方式不会要求指定方法的名字。如果我硬给update指定一个：
@Action(value="update")，会报错！提示找不到对应的action。

难道rest方式下就没有办法将拦截器添加到method级别上么？郁闷。。。