【发布时间】:2015-03-15 20:51:28
【问题描述】:
我正在使用来自 https://spring.io/guides/gs/rest-service/ 的示例,并将默认类 Greeting 更改为我自己的类,当我在网络浏览器 http://localhost:8080/greeting 中调用它时,我得到了答案:
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
我的控制器:
package rest;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import database.*;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
private DBAccess dbaccess= new DBAccess();
@RequestMapping("/greeting")
public Customer greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Customer(1,"a","b");
}
}
和客户类:
package database;
public class Customer {
private long id;
private String firstName, lastName;
public Customer(){};
public Customer(long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
void setFirstName(String firstName){
this.firstName=firstName;
}
void setLastName(String lastName){
this.lastName=lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
在Spring MVC Rest / JSON service 之后,我添加了jackson mapper 依赖项,但它不起作用...
请帮帮我
根据星云评论。 我没有 web.xml,我使用的是来自 https://spring.io/guides/gs/rest-service/ 的示例,但没有。
这是我的 Application.class
package rest;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
【问题讨论】:
-
你有
web.xml吗?也没有为组件扫描提供包。如果 rest 是您的基本包,则应该类似于@ComponentScan("rest")。 -
不,我没有 web.xml。更改为 @ComponentScan("rest") 后,它仍然给出相同的错误... :(
-
如果你没有 web.xml 那么应该有一个实现
WebApplicationInitializer的类。你有这样的课吗? -
等一下。您是否按照该教程尝试使用 Spring Boot?
-
我正在关注本教程,并且在 pom.xml 中我有
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>所以我猜是的,我正在使用 Spring boot
标签: java json spring rest spring-mvc