문제

I am creating a test application to to achieve conversion from JSON String to Employee Object before being passed to the controller.

Here are the key steps performed

  • Creation of Employee.java Class : Domain Object
  • Creation of EmployeeManagementController.java class : Spring MVC Controller for Managing Employee
  • Creation of EmployeeConverter.java : Custom Converter for Converting JSON String to Employee Object.
  • Creation of employee-servlet.xml : Spring Configuration file
  • Creation of web.xml : The Deployment Descriptor

Employee.java

package com.bluebench.training.domain;

import org.springframework.stereotype.Component;

@Component("employee")
public class Employee {

    private PersonalDetail personal;
    private EducationDetail education;
    private WorkExperienceDetail experience;


    // Getters and Setters

}

other domain objects are also defined

EmployeeManagementController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bluebench.training.domain.Employee;

@Controller
public class EmployeeManagementController {

    @RequestMapping(value="/ems/add/employee",method=RequestMethod.POST,consumes="application/json",produces="application/json")
    public @ResponseBody int addEmployee(@RequestBody Employee emp){
        System.out.println("RAGHAVE");
        System.out.println(emp.getPersonal().getName());
        int empId = 20;
        return empId;
    }




}

EmployeeConverter.java

package com.bluebench.training.converter;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.convert.converter.Converter;

import com.bluebench.training.domain.Employee;

public class EmployeeConverter implements Converter<String,Employee>{

    @Override
    public Employee convert(String json) {
        System.out.println("Inside convert()");
        Employee emp = null;
        try {
            emp = new ObjectMapper().readValue(json,Employee.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return emp;
    }




}

employee-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/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="com.bluebench.training"/>

                <mvc:annotation-driven  conversion-service="conversionService"/>

                <mvc:default-servlet-handler/>          

                <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
                    <property name="mediaTypes">
                        <map>
                            <entry key="json" value="application/json" />
                            <entry key="xml" value="text/xml" />
                            <entry key="htm" value="text/html" />
                        </map>
                    </property>
                    <property name="defaultContentType" value="text/html"/>
                </bean>

                <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
                    <property name="converters">
                        <list>
                            <bean class="com.bluebench.training.converter.EmployeeConverter"/>
                        </list>
                    </property>
                </bean>

            </beans>

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" id="WebApp_ID" version="2.5">
  <display-name>PROJECT_38_SpringMVCRESTFul</display-name>

  <servlet>
    <servlet-name>employee</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>employee</servlet-name>
  <url-pattern>/*</url-pattern>
  </servlet-mapping>

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

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



</web-app>

I am using Firefox RestClient to Test it.

Here is the JSON which correctly maps to the Employee object.

{"personal":{"name":"Raghave","age":33,"phoneNumber":"9594511111","address":"101, software appartment, software land , mumbai"},"education":{"qualifications":[{"insititute":"Amity University","degree":"Bachelor of Science","yearOfPassing":"2007","percentage":62.0}]},"experience":{"experience":[{"companyName":"QTBM","designation":"Programmer","years":3,"salary":12000.0},{"companyName":"Polaris","designation":"Software Developer","years":1,"salary":24000.0},{"companyName":"Ness","designation":"Senior Software Engineer","years":2,"salary":50000.0},{"companyName":"JPMC","designation":"Senior Applications Developer","years":1,"salary":120000.0}]}}

There is no Exception thrown and the controller does receive the Employee Object in the addEmployee() method. But its not via converter. The Converter is not invoked. I dont know why ? I dont want to use init binders or @Valid. I wanted to know where am i going wrong. how to make it work?

도움이 되었습니까?

해결책

You've confused Spring's general type conversion support that uses Converters and the ConversionService with its support for HTTP message conversion that is specifically designed for converting web requests and responses and understands media types (like application/json that you're using). HTTP message conversion uses instance of HttpMessageConverter.

You don't actually need a custom converter in this case. Spring's MappingJacksonHttpMessageConverter is being used to perform the conversion automatically. The conversion can be performed automatically because, presumably (you haven't posted the setters so I'm making an educated guess), the setter methods in Employee match the JSON, i.e. setName, setAge, setPhoneNumber etc.

Arguably, the code that you've got is already working. You can safely delete your custom converter, have the same functionality, and have less code to maintain. If you really want to use a custom converter, you'll need to implement HttpMessageConverter and configure it before/in place of MappingJacksonHttpMessageConverter.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top