Spring MVC(不支持的媒体类型)

时间:2014-06-21 19:52:39

标签: spring spring-mvc

我是Spring MVC的新宠,正在尝试用它来制作一些东西。但是当我试图测试控制器时,我陷入了困境。它提供了不支持的媒体类型,我已阅读并根据文档。我在我的Dispatcher Servlet Context文件中放了一个表达式。

<mvc:annotation-driven />

它应该自动初始化我需要以JSON的形式将我的对象传递给控制器​​的MappingJackson2HttpMessageConverter,并且我在我的类路径中以maven依赖的形式拥有这些库。

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.3.2</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.3.2</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.3.2</version>
</dependency>

所以现在,我有MVC命名空间的东西,在classpath中有消息转换器json库但是它仍然在抛出错误。这是我的测试文件。

PersonControllerTest.java

package com.prateekj.controllers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.prateekj.maker.PersonMaker;
import com.prateekj.model.Person;
import com.prateekj.services.PersonService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static com.natpryce.makeiteasy.MakeItEasy.a;
import static com.natpryce.makeiteasy.MakeItEasy.make;
import static com.natpryce.makeiteasy.MakeItEasy.with;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:/configuration/Beans.xml")
public class PersonControllerTest {

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Autowired
  private PersonService personService;

  private Person person;

  private Integer DEFAULT_ID = 2;

  @Before
  public void setUp(){
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
  }

  @Test
  public void shouldAddTheUser() throws Exception {
    person = make(a(PersonMaker.Person, with(PersonMaker.id, (Integer)null)));

    mockMvc.perform(put("/users/add").contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(person)))
        .andExpect(status().isCreated());

    verify(personService).savePerson(person);
  }
}

Beans.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:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.    springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

  <jpa:repositories base-package="com.prateekj.repositories"/>
  <context:component-scan base-package="com.prateekj.services"/>
  <context:component-scan base-package="com.prateekj.controllers"/>

  <bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
    <property name="config">
      <bean class="org.jasypt.encryption.pbe.config.SimpleStringPBEConfig">
        <property name="algorithm" value="PBEWithMD5AndDES"/>
        <property name="password" value="password"/>
      </bean>
    </property>
  </bean>

  <bean id="propertyConfigurer"
        class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">
    <constructor-arg ref="configurationEncryptor"/>
    <property name="locations">
      <list>
        <value>classpath:properties/persistence.properties</value>
      </list>
    </property>
  </bean>


  <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
  </bean>

  <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
    <property name="persistenceUnitName" value="mysql-core"/>
  </bean>

  <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="database" value="MYSQL"/>
    <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
    <property name="showSql" value="false"/>
  </bean>

  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${com.prateekj.jdbc.driver}"/>
    <property name="jdbcUrl" value="${com.prateekj.jdbc.url}"/>
    <property name="user" value="${com.prateekj.jdbc.user}"/>
    <property name="password" value="${com.prateekj.jdbc.password}"/>
  </bean>


</beans>

web.xml

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



  <servlet>
    <servlet-name>toDo</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:configuration/mvc-dispatcher-config.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>toDo</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


</web-app>

mvc-dispatcher-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

  <mvc:annotation-driven />

</beans>

PersonController.java

package com.prateekj.controllers;

import com.prateekj.model.Person;
import com.prateekj.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;

@Controller
@RequestMapping(value = "/users")
public class PersonController {

  private PersonService personService;

  @Autowired
  public PersonController(PersonService personService){
    this.personService = personService;
  }

  @RequestMapping(value = "/add", method = RequestMethod.PUT)
  public ResponseEntity<Void> addUser(@RequestBody Person person){
    personService.savePerson(person);
    return new ResponseEntity<Void>(HttpStatus.CREATED);
  }
}

我无法理解,我在这里做了什么错,请看看代码并告诉我我犯了什么错误, 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您的配置文件中缺少许多步骤。

web.xml中,您永远不会启动根应用程序上下文。你需要这样的东西:

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

并且您不使用默认的/WEB-INF/applicationContext.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/configuration/Beans.xml</param-value>
</context-param>

它与您当前的错误无关,但它应该会很快带给您其他问题。

您想要使用JSON,并在pom.xml中正确声明它。但是你忘了告诉spring框架你需要一个JSON转换器。 =&GT;您Unsupported Media Type的原因。您应该在web-dispatcher-config.xml

中添加类似的内容
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>

<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter"
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>   

如果您是Spring MVC的新手,我强烈建议您遵循教程。我只是谷歌搜索并迅速找到2(我目前的帖子使用第二个提取物):