mvc:annotation-driven不解决406错误

时间:2017-09-06 22:02:58

标签: java json spring spring-mvc junit

我正在尝试为Spring编写一个Junit测试用例,经过大量的阅读后,我得到了一切可以返回text / plain的方法。当我试图返回application / json时,我遇到了问题。

关于SO的共识似乎是:使用mvc:annotation-driven。我试过这个(通过根据here创建下面显示的spring-web-servlet.xml。然而,这并没有解决我的问题。任何人都知道我还在做错什么?

spring-web-servlet.xml(在WEB-INF文件夹中)

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />

</beans>

有问题的方法(在HelloService类中)

@GET
@RequestMapping("/json2")
@Produces({"application/json"})
@ResponseBody
public Object getUserInfoJSON(@RequestParam(value="p",defaultValue="0") Integer userId){
    try (Connection conn = conn()) {
        String query = "SELECT * FROM pulse.customer WHERE userId = ?";
        PreparedStatement preparedStmt = conn.prepareStatement(query);
        preparedStmt.setInt(1, userId);
        ResultSet rs=preparedStmt.executeQuery();
        if(rs.next())
            return Json.createObjectBuilder().add("login name", rs.getString("loginName"));

            return Json.createObjectBuilder().add("login name", "shit broke yo!!!");
    }
    catch(SQLException s){
        return "sql exception:"+s.toString();
    }
    catch (NoResultException nre) {
        //throw new UserNotFoundException(userId);
        return "UserNotFoundException";
    } catch (PersistenceException e) {
        //throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        return "WebApplicationException";
    }
}

Junit测试方法(String中的版本完美运行)

   @Test
    public void testUserInfoResponseJSON() throws Exception{

      MvcResult result=mockMvc.perform(get("/helloservice/json2?p=103")
              .contentType(MediaType.APPLICATION_JSON))
              .andExpect(status().isOk())
              .andExpect(content().contentTypeCompatibleWith("application/json"))
              .andReturn();

      String content = result.getResponse().getContentAsString();

      assertNotNull(content,"{login name:jbray}");
   } 

如果需要,继承我的pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId> 
        <version>1.5.6.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
        </dependency>
        <!-- Adding RESTEasy support to Bean Validations -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-validator-provider-11</artifactId>
            <version>3.1.4.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-links -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-links</artifactId>
            <version>3.1.4.Final</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.6.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.cache</groupId>
          <artifactId>cache-api</artifactId>
        </dependency>
                      <!--SPRING-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId> 
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.paypal.springboot</groupId>
            <artifactId>resteasy-spring-boot-starter</artifactId>
            <version>2.3.3-RELEASE</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId> 
        </dependency>

        <!--JUNIT-->
        <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.0.RELEASE</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

<dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>javax.json</artifactId>
  <version>1.0.4</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.1.1</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
     <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <scope>test</scope>
 </dependency>

    </dependencies>

1 个答案:

答案 0 :(得分:0)

我详细了解了您的依赖关系和代码,发现您正在使用Glassfish的JSR 353提供程序实现。这些类是org.glassfish.json.JsonObjectBuilderImpl$JsonObjectImpl, org.glassfish.json.JsonStringImpl, and org.glassfish.json.JsonNumberImpl, and javax.json.JsonValue$3 (an anonymous class for the value FALSE)

您需要更改以下代码

return Json.createObjectBuilder().add("login name", rs.getString("loginName"));

return Json.createObjectBuilder().add("login name", "shit broke yo!!!");

return Json.createObjectBuilder().add("login name", rs.getString("loginName")).build().toString();

return Json.createObjectBuilder().add("login name", "shit broke yo!!!").build().toString();

并将getUserInfoJSON()方法的返回类型更改为String。有关JSR 353类的详细说明以及映射到ObjectMapper的信息,请访问https://stackoverflow.com/a/19205116/3530898