无法在Spring RestController中调用REST服务

时间:2018-06-17 17:56:30

标签: java spring spring-mvc spring-restcontroller spring-rest

我使用Spring 5 @RestController实现了REST Web服务。

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ag</groupId>
    <artifactId>myFirstWeb</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>myFirstWeb Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jdbc</artifactId>
            <version>1.0.0.M3</version>
        </dependency>

        <!-- ojdbc6.jar example -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.11</version>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-libs-milestone</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>   

    </repositories>


    <build>
        <finalName>myFirstWeb</finalName>
    </build>
</project>

的web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/spring/*</url-pattern>
  </servlet-mapping>

</web-app>

调度-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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <ctx:component-scan base-package="com.*" />
    <ctx:annotation-config />
    <mvc:annotation-driven />

     <!-- JSON Support -->
    <bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>    

    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
        <property name="username" value="SYSTEM" />
        <property name="password" value="xlri@123" />
    </bean>
</beans>

REST服务

package com.pk;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pk.services.StudentService;
import com.pk.vo.StudentVO;

@RestController
@RequestMapping(value="/first")
public class MyFirst{

    public MyFirst() {
        System.out.println("Webservice 'MyFirst' initialised...");
    }


    @Autowired
    @Qualifier("studentService")
    private StudentService service;

    public StudentService getService() {
        return service;
    }

    public void setService(StudentService service) {
        this.service = service;
    }

    @RequestMapping(value="/hello",method=RequestMethod.GET,produces="application/json")    
    public ResponseEntity<String> sayHello() {      
        StringBuffer strb = new StringBuffer();
        strb.append("{")
            .append("\"message\"")
            .append(":")
            .append("\"Hello, this is my first message\"")
            .append("}");
        ResponseEntity<String> responseEntity = new ResponseEntity<String>(strb.toString(), HttpStatus.OK);
        return responseEntity;
    }


    @RequestMapping(value="/students",method=RequestMethod.GET,produces="application/json")
    public List<StudentVO> getAllStudents(){        
        List<StudentVO> list = null;            
        System.out.println(" Studeent list ");
        try {               
            list = this.service.getAll();               
        }catch(Exception e) {
            e.printStackTrace();
        }           
        return list;
    }
}

我可以调用

/spring/first/hello

但我无法调用

/spring/first/students

它给出的错误是:

HTTP Status 406 – Not Acceptable

然后我将代码更改为

@RequestMapping(value="/students",method=RequestMethod.GET,produces="application/json")
public ResponseEntity<List<StudentVO>> getAllStudents(){        
    List<StudentVO> list = null;
    ResponseEntity<List<StudentVO>> responseEntity = null;      
    System.out.println(" Studeent list ");
    try {

        list = this.service.getAll();

        for(StudentVO vo : list) {
            System.out.println(vo);
        }           

        responseEntity = new ResponseEntity<List<StudentVO>>(list,HttpStatus.OK);
    }catch(Exception e) {
        e.printStackTrace();
    }   

    return responseEntity;
}

虽然它在控制台中打印了所有 vo的,但效果不佳。

它给出了同样的错误:

HTTP Status 406 – Not Acceptable

StudentVO.java

package com.pk.vo;

import java.io.Serializable;

public class StudentVO implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 145L;

    private Integer studentId;
    private String studentName;

    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    @Override
    public int hashCode(){
        int hash = 31;
        int hashFromId = this.studentId.hashCode();
        hash = (7 * hash) + hashFromId;
        return hash;    
    }

    @Override
    public boolean equals(Object object) {
        boolean flag = false;
        StudentVO vo = (StudentVO) object;

        if(vo != null && this.studentId.intValue() == vo.studentId.intValue()) {
            flag = true;
        }

        return flag;
    }

    public String toString() {
        StringBuilder strb = new StringBuilder();
        strb.append("\nStudent-ID ").append(this.studentId).append(",\tStudent-Name ").append(this.studentName);
        return strb.toString();
    }
}

你能告诉我我哪里错了吗?

1 个答案:

答案 0 :(得分:1)

将以下依赖项添加到pom.xml中,您会收到错误,因为spring无法将List序列化为JSON,这是由JSON处理的,但是对于spring 4.1.1+,您必须自己添加这些依赖项:

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