java - 春假服务

标签 java json spring rest spring-mvc

我正在使用 https://spring.io/guides/gs/rest-service/ 中的示例我将默认类 Greeting 更改为我自己的类,当我在网络浏览器中调用它时 http://localhost:8080/greeting我得到答案: 出现意外错误(类型= Not Acceptable ,状态=406)。 找不到可接受的表示

我的 Controller :

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

最佳答案

您可能遇到了 JsonMappingException。

我认为您需要添加 getters/setters 或公开一些属性,因为 Jackson 在序列化您的 Customer 类时可能会感到困惑。

关于java - 春假服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27997702/

相关文章:

java - 从警报中的文本字段获取文本

java - 使用 GSON 从 Java 中的 JSON 字符串获取值

javascript - window.location.reload() 在我的 js 页面中使用 我正在注销 我正在使用 spring security

java - 在 spring mvc 3 中包含 css 和 js 文件

java - 为什么 Java 不允许 Throwable 的泛型子类?

java - 使用 HTTPS URL 连接到远程 mysql 数据库

java - 无法在 Android 上使用 XOAUTH 连接到 Gmail IMAP

json - 使用 Spring MVC、Jackson 和 Hibernate 序列化具有多对多关系的对象

json - EXT Js 复杂 JSON 响应处理 : Grid Insertion

java - 实现 Spring bean 的最佳实践