Thursday, May 29, 2008

Struts, Velocity and flexible Content Type

Using Struts2 I wanted to have an output generated by Velocity with text/xml content type. I struggled couple of minutes to figure out how to change it. I used the force and read the source (org.apache.struts2.dispatcher.VelocityResult) - what a surprise, what a flexibility ;)

protected String getContentType(String templateLocation) {
return "text/html";
My solution to this is simple (just copy-paste):

public class FlexibleVelocityResult extends VelocityResult {

private String contentType = "text/html";

public void setContentType(String contentType) {
this.contentType = contentType;

protected String getContentType(String templateLocation) {
return contentType;
It also requires slight change (addition) in your struts.xml file:

From now on when you want to dispatch your action using new Velocity dispatcher you have to do sth like this:

<result name="success" type="flexVelocity">
<param name="location">velocity/rss/rss.vm</param>
<param name="contentType">text/xml</param>


No comments: