How to Return XML Response in Servlet

Returning XML Response in Servlet

In this sample application, We will show you how to return XML response in Servlet application. This example application has been tested and shared in the same post.

Project Structure

How to Return XML Response in Servlet

Servlet Class (

package com.dineshkrish.service;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dineshkrish.pojo.Product;
import com.dineshkrish.util.XMLConverter;

 * @author Dinesh Krishnan

public class ProductService extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// defining the PrintWriter object
		PrintWriter out = response.getWriter();

		// setting the response type

		// creating product object
		Product product = new Product();

		// setting the attributes
		product.setProductDescription("Fresh Bread");

		// converting object to xml using JAX-B api.




POJO Class (

package com.dineshkrish.pojo;

import javax.xml.bind.annotation.XmlRootElement;

 * @author Dinesh Krishnan

public class Product {

	private int productCode;
	private String productName;
	private String productDescription;

	public int getProductCode() {
		return productCode;

	public void setProductCode(int productCode) {
		this.productCode = productCode;

	public String getProductName() {
		return productName;

	public void setProductName(String productName) {
		this.productName = productName;

	public String getProductDescription() {
		return productDescription;

	public void setProductDescription(String productDescription) {
		this.productDescription = productDescription;


Object to XML Converter (

package com.dineshkrish.util;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.dineshkrish.pojo.Product;

 * @author Dinesh Krishnan

public class XMLConverter {

	public static String convert(Product product) {

		StringWriter writer = new StringWriter();

		if (product != null) {

			try {
				JAXBContext context = JAXBContext.newInstance(Product.class);
				Marshaller marshaller = context.createMarshaller();
				marshaller.marshal(product, writer);
			} catch (JAXBException e) {

		return writer.toString();


Application Home Page (index.html)

<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>XML Web Service</title>

	<h1>Service is running...</h1>


Configuration File (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
	id="WebApp_ID" version="3.0">







How to Return XML Response in Servlet


1. Converting Java Object to XML

Hello, folks, I am a founder of I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.