Archive for category REST

Spring RESTful Webservice + JSON


1. In the Controller

@RequestMapping(method={RequestMethod.GET,RequestMethod.OPTIONS, RequestMethod.POST} ,value=”/product”,headers = “Accept=application/json”)
public ResponseEntity<ProductBO> getProducts(@RequestParam(“id”) String id, @RequestParam(“type”) String type) {

ProductBO prodBO = new ProductBO();
prodBO = service.getProducts(id,type);

HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(“Access-Control-Allow-Origin”, “*”);
responseHeaders.add(“Access-Control-Allow-Methods”, “GET, OPTIONS, POST”);
responseHeaders.add(“Access-Control-Allow-Headers”, “Content-Type”);
responseHeaders.add(“Access-Control-Max-Age”, “86400”);

return new ResponseEntity<ProductBO>(prodBO, responseHeaders, HttpStatus.OK);
}

2. web.xml

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>

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

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

3. rest-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:p=”http://www.springframework.org/schema/p&#8221;
xmlns:context=”http://www.springframework.org/schema/context&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd”&gt;

<context:component-scan base-package=”com.spring.controller” />

<bean class=”org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”/>
<bean class=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>
<property name=”messageConverters”>
<list>
<!– Support JSON –>
<bean class=”org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”/>
</list>
</property>
</bean>

<bean id=”productView”>
<constructor-arg ref=”jaxbMarshaller” />
</bean>

<!– JAXB2 marshaller. Automagically turns beans into xml –>
<bean id=”jaxbMarshaller”>
<property name=”classesToBeBound”>
<list>
<value>com.xyz.domain.ProductBO</value>
</list>
</property>
</bean>
</beans>

Leave a comment