简体   繁体   中英

Not able to invoke REST service in spring RestController

I have implemented REST webservice using Spring 5 @RestController .

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>

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

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

I am able to invoke

/spring/first/hello

But I am not able to invoke

/spring/first/students

The error it gives is:

HTTP Status 406 – Not Acceptable

Then I changed my code to,

@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;
}

It's not working as well, although it prints all the vo's in console.

It gives the same error:

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();
    }
}

Can you please tell me where I am wrong?

Add the following dependencies to your pom.xml, you get the error because spring can not serialize your List to JSON, this is handled by JSON however with spring 4.1.1+ you have to add these dependencies yourself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM