我已经从这里获取信息实现了 Struts2 REST API
Struts2 Rest 插件 http://struts.apache.org/docs/rest-plugin.html
有没有办法在 Struts2 的 Restful 插件中返回自定义响应。
我做了所有必需的更改,例如
struts.rest.content.restrictToGET = false
来自这个问题。 https://stackoverflow.com/questions/7685555/post-request-to-struts2-with-rest-plugin-not-receiving-response/9403583#9403583我仍然收到这个错误
No result defined for action `com.web.Controller.RestDemoController` and result create,
如果我不添加上面的行,我仍然会得到相同的响应。
这是我在中提供的操作struts.xml
:
<action name="restdemo" class="com.web.Controller.RestDemoController">
<interceptor-ref name="customRestStack"></interceptor-ref>
</action>
这满足了所有请求GET
,POST
,PUT
,UPDATE
.
将 post 方法的返回类型从 HttpHeader 更改为 String 后,我仍然收到相同的错误
Error 404: No result defined for action com.web.Controller.RestDemoController and result <?xml version="1.0" encoding="UTF-8"?> <Status><code>200</code><message>Success</message></Status>
这是我为 POST 编写的代码:
public HttpHeaders create(){
System.out.println(envision2Data.toString());
return new DefaultHttpHeaders("create").withStatus(200);
}
这是具有返回类型的 POST 请求方法String
:
public String create(){
System.out.println(envision2Data.toString());
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Status><code>200</code><message>Success</message></Status>";
}
如果我发送 xml 或 json 请求,我会得到完美的响应,我会根据扩展名获取 xml 和 json。
喜欢http://localhost:8080/restdemoapplication/restdemo.xml
, http://localhost:8080/restdemoapplication/restdemo.json
for POST request i do post request like
![enter image description here](https://i.stack.imgur.com/U2BwL.png)
你可以看到我得到的回复。我为帖子编写的方法写在上面,名称为create。我的正文中确实有数据,并且我确实在创建方法中完美地获取了数据。
现在在帖子中,正如我在多个示例中看到的那样
支柱休息 https://github.com/Jacob110/struts2-rest, Stuts2-rest-样本 https://github.com/amolghotankar/struts2-rest-sample, struts2-rest-购物清单 https://github.com/darek/struts2-rest-shopping-list
我不想像这些应用程序那样返回发布请求的响应。我想返回我自己的响应,它将是一个状态代码和这样的消息
<?xml version="1.0" encoding="UTF-8"?> <Status><code>200</code><message>Success</message></Status>
经过一些调试我发现DefaultContentTypeHandlerManager
在 struts2-rest-plugin 中考虑xhtml
作为默认模板。虽然它应该是 XML 或 JSON。
我想回来
code : 1xx,2xx,4xx
message: Success, Fail
当处理 POST 请求时,以 XML 或 JSON 形式显示。
(这个应用程序同时接受非静态请求和静态请求。我可以将 xml 或 json 作为默认模板,但我不希望,因为它会影响非静态请求。)