How to send a JSON response in Spring? - java

I want to return a JSON response from the server in a spring application.
Following is my code snippet.
#RequestMapping(value="getCustomer.action", method = RequestMethod.GET)
public #ResponseBody Customer getValidCustomer(Model model) {
System.out.println("comes");
Customer customer2 = (Customer) customerService
.getCustomer("vvmnbv#jgfj.ghfjg");
System.out.println(customer2.getEmail());
return customer2;
}
But I'm getting an error client-side.

You need to:
Add Jackson JSON Mapper to the classpath
Add <mvc:annotation-driven> to your config
Return Map<Integer, String>
Read: http://blog.safaribooksonline.com/2012/03/28/spring-mvc-tip-returning-json-from-a-spring-controller/

Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go:
#RequestMapping(value = "/getfees", method = RequestMethod.POST)
public #ResponseBody
DomainFeesResponse getFees(
#RequestHeader(value = "userName") String userName,
#RequestHeader(value = "password") String password,
#RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) {
return domainFeesHelper.executeRetreiveFees(userName, password, syncDate);
}
Just a little summary: As you know you will need the Jackson library in the class path so that Objects can be converted to JSON.
#ResponseBody tells spring to convert its return value and write it to the HTTP Response automatically. There is no other configuration required.

The sample *-servlet.xml configuration is given below.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.smarttechies.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"></entry>
<entry key="json" value="application/json"></entry>
<entry key="xml" value="application/xml"></entry>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
</beans>
Then deploy the application into server and send the request by setting the “Accept” header to “application/json” to get the response in JSON format or “application/xml” to get the response in XML format.
The detailed post explaining about the spring REST is available at http://smarttechie.org/2013/08/11/creating-restful-services-using-spring/

//I have created a class for converting simple string into json convertable format
and returned it to the JSP page where it parsed into json and used like
public class Json {
public static String Convert(Object a,Object b){
return " \""+a.toString()+"\" : \""+b.toString()+"\",";
}
public static String ConvertLast(Object a,Object b){
return " \""+a.toString()+"\" : \""+b.toString()+"\" }";
}
public static String ConvertFirst(Object a,Object b){
return "{ \""+a.toString()+"\" : \""+b.toString()+"\",";
} }
//Controller code ignore the data that i put into the conver(),convertLast() and convertFirst() methods
String json = Json.ConvertFirst("apId", appointment.getId())
+ Json.Convert("appDate",
format.format(appointment.getAppointmentdate()))
+ Json.Convert("appStart", formathourse.format(appointment
.getAppointmentstarttime()))
+ Json.Convert("appEnd", formathourse.format(appointment
.getAppointmentendtime()))
+ Json.Convert("PatientId", appointment.getPatientId()
.getId())
+ Json.Convert("PatientName", appointment.getPatientId()
.getFname()
+ " "
+ appointment.getPatientId().getLname())
+ Json.Convert("Age", appointment.getPatientId().getAge())
+ Json.Convert("Contact", appointment.getPatientId()
.getMobile())
+ Json.Convert("Gender", appointment.getPatientId()
.getSex())
+ Json.ConvertLast("Country", appointment.getPatientId()
.getCountry());
return json;}
/JSP JQuery Code
var app=jQuery.parseJSON(response);
$("#pid").html(app.PatientId);
$("#pname").html(app.PatientName);
$("#pcontact").html(app.Contact);

Related

Error 415 - Unsupported Media Type with Spring 4

I am upgrading Spring from version 3 (XML based) to 4.2.4 (annotation based)
Controller
#RestController
public class XnetOrderResourceController{
#Autowired
private XnetOrderDao orderDao;
/*
* GET All Orders
*/
#RequestMapping(value = "/getAllOrdersInfo", method =RequestMethod.GET, produces="application/json")
public XnetOrder get(#RequestParam("Id") Long Id) {
XnetOrder order=null;
try{
if(MiscUtils.isNotEmpty(Id)){
order=orderDao.get(Id);
}
}catch(HibernateException e){
log.info(ORDER_DETAIL_NOT_AVAILABLE);
getLogger().error(e.getMessage());
}
return order;
}
/*
* POST(create new) Orders
*/
#RequestMapping(value = "/insertOrders", method =RequestMethod.POST, consumes="application/json", produces="application/json")
public void post(#RequestBody XnetOrder order){
try{
orderDao.post(order);
}catch(HibernateException e){
log.info("Creating the Order operation failed.");
getLogger().error(e.getMessage());
}
}
/*
* PUT (update) orders
*/
#RequestMapping(value="/updateOrders", method=RequestMethod.PUT, consumes="application/json", produces="application/json")
public XnetOrder update(#RequestBody XnetOrder order){
try{
order=orderDao.put(order);
}catch(HibernateException e){
getLogger().error(e.getMessage());
}
return order;
}
/*
* DELETE orders
*/
#RequestMapping(value="/deleteOrders",method=RequestMethod.DELETE)
public void delete(#RequestParam("Id") Long Id){
try{
if(MiscUtils.isNotEmpty(Id)){
orderDao.delete(Id);
log.info("Order is successfully deleted");
}
}catch(HibernateException e){
log.info(XNET_PRODUCT_INVALID_ERROR_MESSAGE);
getLogger().error(e.getMessage());
}
}
}
Spring-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<context:annotation-config />
<context:component-scan base-package="com.nest.extranet" />
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="mediaTypes">
<value>
json=application/json
</value>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
JAR files in my classpath are -
jackson-annotations-2.2.3.jar,
jackson-core-2.2.3.jar,
jackson-databind-2.3.3.jar,
jackson-mapper-asl-1.9.13.jar,
jackson-2.1.0-all.jar
I am able to perform GET operation, which successfully returns JSON value, but PUT and POST operations don't work. I am using Postman as a REST client. I also tried passing the URL for PUT operation after setting the header value Content-Type to aplication/json but it always returns
Error 415 - Unsupported Media Type.
I am getting the following response headers:
Connection → close
Content-Length → 903
Content-Type → text/html; charset=UTF-8
Date → Sat, 14 May 2016 09:16:57 GMT
X-Powered-By → Servlet/2.5 JSP/2.1
Can someone please suggest how to get PUT and POST operations to work?
If you specify produces for the controller method you also need to set the Accepts header on the request.

Declartive Transaction in spring is not working

I am using spring declarative Transaction features. Something like this
XML file for spring configuration..
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<context:component-scan base-package="com" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Add this tag to enable annotations transactions -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
Dao Layer code
package com.dao;
#Repository("commonDao")
public class CommonDaoImpl implements CommonDao {
private static Logger logger = Logger.getLogger(CommonDaoImpl.class);
#Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
#Autowired
public void setSessionFactory(){
jdbcTemplate = new JdbcTemplate(dataSource);
}
#Override
public Object makePayment(Object e) {
String sql = "insert into payment (id, name, amount) values('abc', 100)";
try{
return jdbcTemplate.update(sql);
}catch(DataAccessException ex){
throw ex;
}
}
#Override
public Object signUp(Object e) {
String sql = "insert into login (userid, password) values('naveen', 'password')";
return jdbcTemplate.update(sql);
}
}
Service Layer code
#Service
public class CommonServiceImpl implements CommonService {
#Autowired
private CommonDao commonDao;
// #Transactional I tried both of them one by one but not worked
#Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
#Override
public boolean makePayment() {
try{
commonDao.signUp(new Object());
commonDao.makePayment(new Object());
} catch(DataAccessException ex){
return false;
}
return true;
}
}
but when i send call makePayment() method via controller then it save the record into login table but failed when it move to insert into payment table because i write query so that it can through an exception. I do not understand why transaction is not working. because #Transactional annotation is on makePayment method so not operation should happen in db.
Please tell what's wrong in this code.
Your SQL query in in makePayment method is :
insert into payment (id, name, amount) values('abc', 100)
You are asking the query to insert id, name and amount in the database table, but providing only 2 values i.e. abc and 100.
If id column in the table is autoincrement id then you don't need to mention it in the SQL query. Your SQL query in the makePayment method should be like this:
insert into payment (name, amount) values('abc', 100)

How would I create the function for sending an email with the parameters set as String from, String to, String Subject, and String body?

I am trying to create a java batch email program that will send an email to a specific inbox with an excel report attachment. I have the function:
public void sendEmail(String to, String from, String subject, String body)
{
}
I am trying to use Spring, and I'm trying to stick to xml configuration in the appcontext file for now instead of annotations (for learning purposes). I want to inject a static resource which is an excel file, and for learning purposes for this module I am avoiding using FileSystemResource for the attachment per my mentor/teacher. I also don't need the body to say anything. The subject line will be "Report" for dummy purposes. Here is what I have so far, just need the meat of the actual email function that's needed so I could pass the parameters of sendEmail by reference in the main class:
public class SendEmail
{
private JavaMailSender mailSender;
public SendEmail(JavaMailSender ms)
{
this.mailSender = ms;
}
public void sendEmail(String from, String to, String Subject, String body)
{
MimeMessage message = mailSender.createMimeMessage();
try
{
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("whatever#xyz.com");
helper.setText("Test email!");
mailSender.send(message);
}
catch (MessagingException e)
{
throw new MailParseException(e);
}
}
public void setMailSender(JavaMailSender mailSender)
{
this.mailSender = mailSender;
}
}
This is the applicationContext.xml code:
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.transportation"/>
<bean id = "mailSender" class = "org.springframework.mail.javamail.JavaMailSenderImpl">
<property name = "host" value = "Whatever" />
<property name = "port" value = "25" />
</bean>
<bean id = "sendEmail" class = "com.transportation.email.util.SendEmail">
<constructor-arg ref="mailSender"/>
</bean>
</beans>
Try this one.
public void sendMail(final String messageStr, final boolean isHtml) throws MessagingException {
final MimeMessage message = mailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setCc(simpleMailMessage.getCc());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(messageStr, isHtml);
helper.addInline("myFile", ResourceUtil.loadResourceAsFileSystemResource("NameOfresource"));
mailSender.send(message);
}
public static FileSystemResource loadResourceAsFileSystemResource(final String fileRoute) {
File file = null;
FileSystemResource fileSystemResource;
try {
file = new ClassPathResource(fileRoute).getFile();
fileSystemResource = new FileSystemResource(file);
}
catch (final IOException e) {
fileSystemResource = null;
}
return fileSystemResource;
}
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.host">${mail.smtp.host}</prop>
<prop key="mail.smtp.port">${mail.smtp.port}</prop>
</props>
</property>
</bean>
<bean id="sfErrorMailSender" class="XXX.MailSender">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="sfErrorNotificationMailMessage" />
</bean>
<bean id="sfErrorNotificationMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.message.error.sf.to}" />
<property name="to" value="${mail.message.error.sf.from}" />
<property name="subject" value="${mail.message.error.sf.subject}" />
<property name="text" value="${mail.message.error.sf.body}" />
<property name="cc" value="${mail.message.error.sf.cc}" />
</bean>

Spring MVC & Freemarker session attribute not exposed

I've got a problem with Freemarker's viewResolver with Spring - session attributes are not exposed to view, as it is in Spring's InternalResourceViewResolver.
Now, important part is: when I change from Spring's resolver to Freemarker's one, session attribute is not passed, it's null. When Spring's resolver is working, session is passed.
My code:
dispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<bean id="userSession" class="com.revicostudio.web.session.UserSession" scope="session">
</bean>
<context:component-scan base-package="com.revicostudio.web" />
<mvc:annotation-driven />
<!--
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape"/>
</map>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".jsp"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="exposeRequestAttributes" value="true"/>
<property name="allowRequestOverride" value="false" />
<property name="exposeSessionAttributes" value="true"/>
<property name="allowSessionOverride" value="false" />
<property name="exposePathVariables" value="true"/>
</bean>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/ftl/" />
<property name="suffix" value=".jsp" />
<property name="exposeContextBeansAsAttributes" value="true" />
</bean>
</beans>
LoginController.java:
#Controller
#RequestMapping("/login")
#SessionAttributes("userSession")
public class LoginController {
#Autowired
private UsersDatabaseService usersDatabaseService;
#RequestMapping(method = RequestMethod.POST)
public String login(
#ModelAttribute UserLoginCredentials userLoginCredentials,
UserSession userSession,
final RedirectAttributes redirectAttributes)
{
int failedLoginAttempts = userSession.getFailedLoginAttempts();
if (failedLoginAttempts < LoginConfig.maxLoginTries ||
System.currentTimeMillis()-userSession.getFailedLoginsWaitTimeStart() > LoginConfig.failedLoginsWaitMinutes*60*1000) {
if (usersDatabaseService.isValidPassword(userLoginCredentials.getUsername(), userLoginCredentials.getPassword())) {
userSession.setUser(usersDatabaseService.getUser(userLoginCredentials.getUsername()));
userSession.setFailedLoginsWaitTimeStart(System.currentTimeMillis());
}
else {
failedLoginAttempts++;
if (failedLoginAttempts == LoginConfig.maxLoginTries) {
redirectAttributes.addFlashAttribute("error",
"You've entered invalid username or password more than "
+ LoginConfig.maxLoginTries + " times. Try again in "
+ LoginConfig.failedLoginsWaitMinutes +" minutes.");
}
else {
redirectAttributes.addFlashAttribute("error", "Invalid username or password");
userSession.setFailedLoginAttempts(failedLoginAttempts);
System.out.println(failedLoginAttempts);
}
}
}
else {
redirectAttributes.addFlashAttribute("error",
"You've entered invalid username or password more than "
+ LoginConfig.maxLoginTries + " times. Try again in "
+ LoginConfig.failedLoginsWaitMinutes +" minutes.");
}
return "redirect:/";
}
}
IndexController:
#Controller
#RequestMapping("/index")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public String getIndex(Model model) {
return "index";
}
#ModelAttribute("userRegisterCredentials")
public UserRegisterCredentials getUserRegisterCredentials() {
return new UserRegisterCredentials();
}
#ModelAttribute("userLoginCredentials")
public UserLoginCredentials getUserLoginCredentials() {
return new UserLoginCredentials();
}
}
index.jsp:
<body>
<!-- Code for Freemarker -->
<#if error??>
${error}
</#if>
<#if userSession??>
${userSession}
</#if>
<#if !(userSession??)>
b
</#if>
<!-- Code for JSTL -->
${userSession}
You have a session problem because of that redirectAttributes.addFlashAttribute(). which means addFlashAttribute actually stores the attributes in a flashmap (which is internally maintained in the users session and removed once the next redirected request gets fulfilled),
Just try without redirectAttributes.addFlashAttribute() you will get session.
May be this will help you

Spring MVC - marshalling an XML parameter to object (JAXB) in a multipart request

I created a file upload service using Spring MVC with apache commons multipart resolver support which specifies that a file should be attached as part of a multipart HTTP Post request. The request also contains a parameter containing an XML string with meta-data about the object. The XML can be marshalled using JAXB.
Other services that are not multipart handle the marshalling transparently, e.g.:
#RequestMapping(value = "/register", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public ModelAndView createUser(#RequestBody CreateUserDTO createUserDTO) throws Exception {
UserDTO user = userService.createUser(createUserDTO);
return createModelAndView(user);
}
Here CreateUserDTO is a JAXB annotated object which is automatically marshalled.
In the multipart case I'd like to have the same transparency. Ideally I would like to do the following:
RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public ModelAndView createAttachment(#RequestParam AttachmentDTO attachment,
HttpServletRequest request) throws Exception {
final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
AttachmentDTO attachment = null;
final MultipartFile dataFile = multipartRequest.getFile("data");
AttachmentDTO createdAttachment = attachmentService.createAttachment(attachment,
dataFile);
return createModelAndView(createdAttachment);
}
Unfortunately this does not work. I am able to bind the attachment parameter as String, but the automatic marshalling does not work. My work around is to manually do the marshalling like the following, but I don't like this approach (especially since the parameter may be specified both in JSON and XML form):
#Autowired
private Jaxb2Marshaller jaxb2Marshaller;
#Autowired
private ObjectMapper jacksonMapper;
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public ModelAndView createAttachment(#RequestParam(ATTACHMENT_PARAMETER) String attachmentString,
final HttpServletRequest request) throws Exception {
final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
AttachmentDTO attachment = null;
try {
attachment = (AttachmentDTO)jaxb2Marshaller.unmarshal(new StreamSource(new StringReader(attachmentString)));
} catch (XmlMappingException e) {
//Try JSON
try {
attachment = jacksonMapper.readValue(attachmentString, AttachmentDTO.class);
} catch (IOException e1) {
throw new BadRequestException("Could not interpret attachment parameter, both JSON and XML parsing failed");
}
}
Does anyone have a better suggestion for resolving this issue?
For completeness I also specify the relevant Spring config here:
<bean id="viewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="favorPathExtension" value="true"/>
<property name="ignoreAcceptHeader" value="false"/>
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="modelKey" value="object"/>
<property name="marshaller" ref="jaxbMarshaller"/>
</bean>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="objectMapper" ref="jaxbJacksonObjectMapper"/>
</bean>
</list>
</property>
</bean>
<!--Use JAXB OXM marshaller to marshall/unmarshall following class-->
<bean id="jaxbMarshaller"
class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPath" value="com.behindmedia.btfd.model.dto"/>
</bean>
<bean id="jaxbJacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
<!-- allows for integration of file upload functionality -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="maxUploadSize" value="100000000"/>
</bean>

Categories