Struts 2 XML response Annotation example

Struts 2 XML response Annotation example

This code will show you how to return XML response in struts 2 application. Here I have used annotation based struts 2 application and if you are using struts.xml for your configuration then you will have to add action class mapping in your XML file.

  • Project structure:

Struts 2 XML response Annotation example

  • pom.xml:
<project xmlns="" xmlns:xsi=""
  <name>Struts2XMLResponse Maven Webapp</name>

package com.javahonk.action;


import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ActionSupport;

public class XMLResponseAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    @Action(value = "/xMLResponseAction")
    public String execute() throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();

        PrintWriter printWriter = null;
        response.setHeader("Cache-Control", "no-cache");

        StringBuilder stringBuilder = new StringBuilder("<person>");
        try {
            printWriter = response.getWriter();
            stringBuilder.append("<firstName>" + "Java" + "</firstName>");
            stringBuilder.append("<lastName>" + "Honk" + "</lastName>");
        } catch (IOException ioException) {
        } finally {
            printWriter = null;
        return NONE;


  • index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
        <title>Struts 2 XML response Annotation example</title>
        <h2 style="color: green"><s:text name="Struts 2 XML response Annotation example" /></h2>
        <a href="xMLResponseAction">Click here to pull XML data from server</a>        
  • web.xml:
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >

    <display-name>Archetype Created Web Application</display-name>



  • Run application in tomcat server:

Struts 2 XML response Annotation example

and on above page Click here to pull XML data from server it will show you XML data output as below:

Struts 2 XML response Annotation example

For more information please read this struts tutorial

download Download Project:  Struts2XMLResponse

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *