I have a Struts project where I need to send a response as a raw string
struts.xml
:
<struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.ui.theme" value="simple"></constant>
<constant name="struts.xwork.chaining.copyErrors" value="true"></constant>
<constant name="struts.xwork.chainingcopyMessages" value="true"></constant>
<package name="basicstruts6" extends="struts-default" namespace="/">
<default-action-ref name="init"></default-action-ref>
<action name="init" class="some.class.path.mvc.ServiceTestAction" method="init">
<result name="success">/WEB-INF/app/index.jsp</result>
</action>
<action name="invokeService" class="some.class.path.mvc.ServiceTestAction" method="execute">
<result name="success">/WEB-INF/app/index.jsp</result>
</action>
</package>
</struts>
In the <action name="invokeService" class="some.class.path.mvc.ServiceTestAction" method="execute">
I want to repond with a raw string I define without using the index.jsp
file as model.
I still want some.class.path.mvc.ServiceTestAction
to handle the request, but want to write directly to the response writer
And at the same time I want to set the HTTP code of the response. In case it's an error I want to respond with HTTP 400 and write the body directly to the response writer.
If you don't want to return index.jsp as a result then you should remove this code in the struts.xml
<result name="success">/WEB-INF/app/index.jsp</result>
</
In the action class execute()
method where the return SUCCESS
put return NONE
.
You can get HttpServletRequest
and HttpServletResponse
if your action class implements ServletRequestAware
and ServletResponseAware
.
You can also read this answer: How to get the request body and response body in apache struts2? - post using $.ajax.
In the action execute()
method you write to the response some text using the servlet API. Something like
PrintWriter writer = httpServletResponse.getWriter();
writer.println("hello server");
writer.flush();
httpServletResponse.setStatus(400);