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

问题描述 投票:0回答:1

我试图得到一个简单的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合作,但在这里我不知何故失去了。

spring-mvc jetty embedded-jetty
1个回答
0
投票

尝试添加

produces = "application/json"

同样。

© www.soinside.com 2019 - 2024. All rights reserved.