问题
So, I'm using freemarker templates with Struts2 to formulate my responses. However, since I'm trying to use taconite as well, I need the response to be sent with the content type of "text/xml". I can't seem to find a way to use freemarker directives to set the content type, and I am not well versed enough in struts to know if there is a way to do it through that.
So, how should I go about this?
回答1:
Or you can set it in the struts.xml
<action name="..." class="...">
<result name="SUCCESS">
<param name="contentType">text/html</param>
回答2:
In your Action class, implements the ServletResponseAware interface, and use a simple:
package your.package;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
public class YourAction extends ActionSupport implements
ServletResponseAware {
private HttpServletResponse response;
public String execute() throws Exception{
response.setContentType("image/png");
return SUCCESS;
}
public void setServletResponse(HttpServletResponse response){
this.response = response;
}
public HttpServletResponse getServletResponse(){
return response;
}
}
More information here:http://www.roseindia.net/struts/struts2/strutsresources/access-request-response.shtml
回答3:
Implementing ServletResponseAware
might work in other situations, but it doesn't help with Freemarker and Struts2. :-( I just traced it through with a debugger, and found that...
by implementing
ServletResponseAware
, I was given access to the response, and I could change the content-type from my action. Good.once my action was done, control soon ended up in
org.apache.struts2.views.freemarker.FreemarkerResult
, which renders the templatethe method
preTemplateProcess()
sets the response's content-type, ignoring the value I had set :-(apparently there's a "custom attribute" that could be used to override this, but I haven't found any explanation in google yet
the
FreemarkerResult
class itself can have a content-type set to override the default, but... not sure yet where that can be set from, maybe in a struts configuration?
So so far it doesn't seem that the action can set the content-type, but fortunately as Thomas notes above, this overrides all that:
${response.setContentType("text/xml")}
So at least it's possible from the templates. Sure would be easier and safer to give a set of xml-producing actions a common superclass that takes care of this...
回答4:
Or, if you prefer annotations:
@Result(name=SUCCESS, location="...", params={"contentType", "text/html"})
回答5:
Answered my own question:
Use the following code at the type of the template:
${response.setContentType("text/xml")}
来源:https://stackoverflow.com/questions/1671823/setting-the-content-type-of-a-response-in-struts2