views:

1164

answers:

4

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?

A: 

Answered my own question:

Use the following code at the type of the template:

${response.setContentType("text/xml")}
Thomas
+2  A: 

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

Lastnico
This worked for me - not the accepted one.
Fakrudeen
+1  A: 

Or you can set it in the struts.xml

<action name="..." class="...">
  <result name="SUCCESS">
    <param name="contentType">text/html</param>
Ulf Lindback
A: 

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 template

  • the 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...

Rodney Gitzel