RESTFul Spring MVC应用程序需要很长时间才能响应

时间:2014-01-26 18:12:20

标签: java xml json spring spring-mvc

这是我的测试应用程序,我通过post请求传递XML,以便收到JSON响应。

我在应用程序中使用以下组件

  • 创建Employee.java类:域对象
  • 创建EmployeeManagementController.java类:用于管理员工的Spring MVC控制器
  • 创建EmployeeConverter.java:用于将XML字符串转换为Employee对象的自定义转换器。
  • 创建employee-servlet.xml:Spring配置文件
  • 创建web.xml:部署描述符

Employee.java

package com.domain;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.springframework.stereotype.Component;

@Component
@XmlRootElement(name="employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee{

    @XmlElement(name="name")
    String name;
    @XmlElement(name="designation")
    String designation;
    @XmlElement(name="skill")
    String skill;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }
    public String getSkill() {
        return skill;
    }
    public void setSkill(String skill) {
        this.skill = skill;
    }

}

EmployeeManagementController.java

package com.controller;

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.domain.Employee;

@Controller
@RequestMapping(value="/emp")
public class EmployeeManagementController {

    //@RequestMapping(value="/add/employee", method=RequestMethod.POST, consumes="text/html")
    @RequestMapping(value="/add/employee", method=RequestMethod.POST, consumes="text/html", produces="application/json", headers={"Accept=application/json"} )
    public @ResponseBody Employee addEmployee(@RequestBody Employee employee){
        System.out.println("Employee Name : "+employee.getName());
        System.out.println("Employee Designation : "+employee.getDesignation());
        System.out.println("Employee Skill : "+employee.getSkill());
        return employee;
    }   

}

EmployeeConverter.java

package com.converter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;

import com.domain.Employee;

@Component
public class EmployeeConverter extends AbstractHttpMessageConverter<Employee>{


    public EmployeeConverter() {
        // TODO Auto-generated constructor stub
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        super.setSupportedMediaTypes(supportedMediaTypes);
    }

    @Override
    protected Employee readInternal(Class<? extends Employee> arg,  HttpInputMessage inputMsg) throws IOException,
            HttpMessageNotReadableException {
        // TODO Auto-generated method stub
        //System.out.println(inputMsg.getBody().toString());
        Map<String,String> paramMap = getPostParameter(inputMsg);
        BufferedReader file =  new BufferedReader(new StringReader(paramMap.get("xml")));
        Employee employee = null;
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(Employee.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            employee = (Employee) jaxbUnmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(employee);
        return employee;
    }

    @Override
    protected boolean supports(Class<?> type) {
        if(type.getSimpleName().equalsIgnoreCase("Employee")){
            return true;
        }
        return false;
    }

    @Override
    protected void writeInternal(Employee arg0, HttpOutputMessage arg1)
            throws IOException, HttpMessageNotWritableException {
        // TODO Auto-generated method stub

    }

    private Map<String,String> getPostParameter(HttpInputMessage input) throws IOException{
        String payload = "";
        String[] params = null;
        BufferedReader buf = new BufferedReader(new InputStreamReader(input.getBody()));
        Map<String,String> paramMap = new HashMap<String,String>();

        String line="";
        while((line = buf.readLine())!=null){
            payload = payload+line;
        }
        System.out.println(payload);
        if(payload.contains("&")){
            params = payload.split("&");
            for(String param : params){
                paramMap.put(param.split("=")[0],param.split("=")[1]);
            }
        }else if(payload.contains("=")){
            params = payload.split("=");            
            paramMap.put(params[0],params[1]);
        }

        return paramMap;
    }


}

雇员-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"
                xmlns:util="http://www.springframework.org/schema/util"
                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
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util-3.1.xsd">

        <!-- <mvc:default-servlet-handler/>  --> 

        <context:component-scan base-package="com"/>

         <!-- <mvc:annotation-driven>
            <mvc:message-converters register-defaults="false">
                <bean class="com.converter.EmployeeConverter"/>             
            </mvc:message-converters>
        </mvc:annotation-driven>  --> 

        <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="defaultViews">
                <list>
                    <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
                </list>
            </property>
            <property name="defaultContentType" value="text/html"/>
        </bean>

         <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">    
                <list>
                    <ref bean="employeeConverter"/>
                    <ref bean="jacksonMessageConverter"/>                          
                </list>
            </property>
        </bean>

         <bean id="employeeConverter" class="com.converter.EmployeeConverter"/>  
        <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>


</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>TestConverter</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>    
  </welcome-file-list>

  <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>

我使用RESTClient发出一个post请求,并将xml作为参数

xml=<employee><name>Jack</name><designation>Account Director</designation><skill>Commuication</skill></employee>

我使用RESTClient

在请求中设置了以下标头

的Content-Type = text / html的 接受=应用/ JSON

但是当我发送请求时,Controller方法执行得非常快速,但似乎响应生成时间太长,在发送请求后,RESTClient根本没有收到响应。

如果这段代码因为我没有使用writeInternal()方法转换响应而破解,那么这对我来说有点令人失望,因为我们为什么要在转换请求时强制转换响应。对于响应转换,我希望使用spring的MappingJackson2JSONConverter。这不可能吗?

提前致谢

0 个答案:

没有答案