java 使用ajax调用Struts 2动作,直接向响应写入字符串不返回字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17133243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a Struts 2 action using ajax, which write a string directly to the response does not return the string
提问by Harshana
In a struts2 application I am calling a Ajax request in and write a string directly to the response as below and return null
in the execute method of the action.
在 struts2 应用程序中,我正在调用 Ajax 请求并将字符串直接写入响应,如下所示,并null
在操作的执行方法中返回。
ServeletActionContext.getResponse().getOutputStream().print("sample string");
return null;
In struts.xml
I have the below declaration, (below is how the application declares the actions with result types which are working fine. In my case since I don't need result to invoke a JSP or another action, I did not add the result tag)
在struts.xml
我有以下声明,(以下是应用程序如何声明具有正常工作的结果类型的操作。在我的情况下,由于我不需要结果来调用 JSP 或其他操作,我没有添加结果标记)
<action name="controller" class="controller">
And I map the section class in the application-context.xml
我将部分类映射到 application-context.xml
<bean id="controller" class="com.test.ControllerAction" scope="prototype">
Then I have the ajax call as below,
然后我有如下的ajax调用,
$.ajax({url:"/root/me/controller.action",success:function(result){
alert(result);
}});
But the problem is in above instead of alerting the "sample string"
which I wrote for the response, it alerts the whole JSP page where the above Ajax call resides. What am I missing here?
但问题出在上面,而不是提醒"sample string"
我为响应编写的内容,而是提醒上述 Ajax 调用所在的整个 JSP 页面。我在这里错过了什么?
回答by Roman C
Return result type stream
by default it outputs text.
返回结果类型stream
默认输出文本。
<action name="controller" class="ControllerAction">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">stream</param>
</result>
</action
stream
should be the property type ImputStream
;
stream
应该是属性类型ImputStream
;
public class ControllerAction extends ActionSupport {
private InputStream stream;
//getter here
public InputStream getStream() {
return stream;
}
public String execute() throws Exception {
String str = "sample string";
stream = new ByteArrayInputStream(str.getBytes());
return SUCCESS;
}
}
回答by sithum
Instead of using
而不是使用
ServeletActionContext.getResponse().getOutputStream().print("sample string");
return null;
use this code
使用此代码
PrintWriter out = response.getWriter();
out.write("sample string");
return null;
This should work.
这应该有效。