Struts2 JSON拦截器没有填充我的Action类 [英] Struts2 JSON interceptor not populating my Action class
问题描述
我正在开发一个Web应用程序,其中客户端JavaScript库(ExtJS)使用JSON请求有效负载向启用Struts的后端发送请求。我的问题是我无法弄清楚如何将有效载荷中的变量导入我的Action类。
I am working on a web app in which the client JavaScript library (ExtJS) sends requests to my Struts-enabled backend with a JSON request payload. My problem is that I can't figure out how to get the variables from the payload into my Action class.
我从使用日志语句知道我的正确方法前端正在调用action类。只是我期待的变量是 null
,当它们不应该是。
I know from using log statements that the correct method in my action class is being called by the frontend. It's just that the variables I am expecting are null
when they shouldn't be.
我正在尝试使用 struts2-json-plugin
作为拦截器。 Struts拦截器对我来说是新手,我无法在网上找到任何关于以这种方式使用 struts2-json-plugin
的明确示例。
I'm trying to use struts2-json-plugin
as an interceptor. Struts interceptors are new to me, and I haven't been able to find any clear examples on the web about using struts2-json-plugin
in this way.
以下是我的 pom.xml中的Struts依赖项
:
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.2.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.2.3.1</version>
</dependency>
这是请求正文(照顾Firebug):
Here is the request body (care of Firebug):
{"id":15,"translation":"Blah blah"}
我的Action类的相关部分如下所示:
The relevant parts of my Action class look like this:
public class TranslationsAction extends ActionSupport {
private Long id;
private String translation;
public String save() throws Exception {
log.debug("TranslationsAction.save() called.");
log.debug("ID: " + this.id + ", Translation: " + this.translation);
return "{\"foo\":\"bar\"}";
}
public void setId(Long id) {
this.id = id;
}
public void setTranslation(String translation) {
this.translation = translation;
}
}
这是我的相关部分 struts.xml
:
<package name="foo" namespace="/foobar" extends="json-default">
<action name="save-translation" method="save"
class="my.package.name.action.TranslationsAction">
<result name="success">/jsp/json.jsp</result>
</action>
</package>
任何想法?
推荐答案
我自己发现了这个问题。我无法正确配置 struts.xml
。我需要首先在我的包中定义一个拦截器,然后告诉我的操作使用它,如:
I found the problem myself. I had failed to configure struts.xml
properly. I needed to first define an interceptor within my package, and then tell my action to use it, as in:
<package name="foo" namespace="/foobar" extends="json-default">
<!-- Added this: -->
<interceptors>
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
</interceptors>
<action name="save-translation" method="save"
class="my.package.name.action.TranslationsAction">
<!-- And added this: -->
<interceptor-ref name="myDefaultInterceptorStack" />
<interceptor-ref name="json" />
<result name="success">/jsp/json.jsp</result>
</action>
</package>
这对我来说是一个愚蠢的疏忽。 :-\
It was a silly omission on my part. :-\
这篇关于Struts2 JSON拦截器没有填充我的Action类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!