应用程序/ json的Jetty / SpringMVC不支持的媒体类型

时间:2018-03-03 10:05:20

标签: spring-mvc jetty embedded-jetty

我想尝试一个简单的Jetty / SpringMVC示例,并且遇到了一个我无法解决的问题。

我使用的课程如下:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class JettyTest {

  public static void main(String[] args) throws Exception {
    AnnotationConfigWebApplicationContext spring = new AnnotationConfigWebApplicationContext();
    spring.scan("controllers");

    DispatcherServlet servlet = new DispatcherServlet(spring);
    ServletHolder servletHolder = new ServletHolder(servlet);
    servletHolder.setName("spring");

    ServletContextHandler springHandler = new ServletContextHandler(
        ServletContextHandler.NO_SESSIONS);
    springHandler.setContextPath("/");
    springHandler.addServlet(servletHolder, "/*");
    springHandler.setErrorHandler(null);
    springHandler.addEventListener(new ContextLoaderListener(spring));

    Server server = new Server(5050);
    server.setHandler(springHandler);
    server.setStopAtShutdown(true);
    server.start();
    server.join();
  }
}

控制器:

package controllers;

import model.MessageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

  @RequestMapping(value = "/message", method = RequestMethod.POST, consumes = "application/json")
  public ResponseEntity<String> testPost(@RequestBody MessageRequest messageRequest) {
    return new ResponseEntity<>("POST Response: " + messageRequest.getMessage(), null,
        HttpStatus.OK);
  }
}

最后是MessageRequest类:

package model;

public class MessageRequest {
  private String message;

  public void setMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }
}

但是,当我启动此应用程序并使用以下请求正文发送POST请求时:

{
    "message" : "test"
}

我收到以下回复:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
        <title>Error 415 Unsupported Media Type</title>
    </head>
    <body>
        <h2>HTTP ERROR 415</h2>
        <p>Problem accessing /message. Reason:

            <pre>    Unsupported Media Type</pre>
        </p>
        <hr>
        <a href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.8.v20171121</a>
        <hr/>
    </body>
</html>

我做错了什么?我有一个类似的例子可以使用Springboot,但是我在这里丢失了。

1 个答案:

答案 0 :(得分:0)

尝试添加

produces = "application/json"