Spring MVC View JSON | XML | PDF

Building REST service using Spring MVC that returns different media type json, xml or pdf.

Objective

  • How to build a REST service using Spring MVC to return json, xml  or pdf?

Environment

  • Eclipse (Indigo) or any other version
  • Jetty (eclipse-plugin) or any other server

Libraries

( 1 ) Create Java Project

create java project with the following directory structure, copy jar files to “lib” folder

( 2 ) Java Classes

MyController.java

This class receives the request.

package com.hmkcode.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hmkcode.vo.Person;

@Controller
public class MyController {

	@RequestMapping("/view")
	public Person getPerson(Model model){
		Person person = new Person();
		person.setId(1);
		person.setName("hmk");
		model.addAttribute("person",person);
		return person;
	}

}

PdfView.java

This class builds PDF using iText.

package com.hmkcode.view;

import java.util.List;
import java.util.Map;

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

import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.hmkcode.vo.Person;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class PdfView extends AbstractPdfView {

    protected void buildPdfDocument(
        Map model,
        Document doc,
        PdfWriter writer,
        HttpServletRequest req,
        HttpServletResponse resp)
        throws Exception {

        System.out.println("pdf");
        Person person = (Person) model.get("person");
        doc.add( new Paragraph(person.toString()));

    }
}

Person.java
Just POJO.

package com.hmkcode.vo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "person")
public class Person {

	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String toString(){
		return "ID: "+id+" - Name: "+name;
	}

}

( 3 ) web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

( 4 ) Spring XML Configuration (springmvc-servlet.xml)

springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
	<beans 	xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:context="http://www.springframework.org/schema/context"
		xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context.xsd">

	<context:component-scan base-package="com.hmkcode.controllers" />
		 	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
	  <property name="order" value="1" />
	  <property name="mediaTypes">
		<map>
		   <entry key="json" value="application/json" />
		   <entry key="xml" value="application/xml" />
		   <entry key="pdf" value="application/pdf" />

		</map>
	  </property>

	  <property name="defaultViews">
		<list>
		  <!-- JSON View -->
		  <bean
			class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
		  </bean>
		  <!--  XML view -->
   			<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
			<constructor-arg>
				<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
				   <property name="classesToBeBound">
					<list>
					   <value>com.hmkcode.vo.Person</value>
					</list>
				   </property>
				</bean>
			</constructor-arg>
		  </bean>
		  <!--  PDF view -->
		  <bean class="com.hmkcode.view.PdfView">

		    </bean>
		 </list>
	  </property>
	  <property name="ignoreAcceptHeader" value="true" />

	</bean>
</beans>

( 5 ) Deploy and Run

Download Source Code: SpringMVC.zip

One thought on “Spring MVC View JSON | XML | PDF

  1. Brett Delia

    I was curious if you knew why when I submit a POST request with the JSON flag set that the response does not return the expect JSON? It appears that instead the response is either timing out and returning a response status of 0.

Comments are closed.