首页 > 解决方案 > 为什么我在 Spring MVC 中得到 415 Unsupported Media Type?

问题描述

我收到以下错误;我尝试了一切但没有得到解决方案:

HTTP Status 415 – Unsupported Media Type 

我正在尝试将 JSON 对象发送到控制器,并将其放入@Requestbody

<%@page import="org.json.JSONObject"%>
<%@ page language="java" contentType="application/json charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome</h1>

<a href="./getRegister">Register</a>
<a href="./delete?id=1">Delete</a>

<%
    JSONObject obj = new JSONObject();
    obj.put("id", "1");
    obj.put("name", "ABC");
%>

<form action="./jsonreq" method="post">
    <input type="hidden" name="obj" id="obj" value="<%=obj%>">
    <input type="submit" value="Submit"/>
</form>
</body>
</html>

2)控制器:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springhibernate.bean.Employee;
import com.springhibernate.service.EmployeeService;

@Controller
public class RegistrationController {



    @RequestMapping(path="/jsonreq", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Employee json(@RequestBody Employee obj) 
    {
        System.out.println("JSON"+obj.toString());
        return obj;
    }

}

标签: jsonspringspring-mvcspring-rest

解决方案


您将获得 415 状态,因为您的浏览器正在向application/x-www-form-urlencoded仅接受的控制器方法发送内容类型为 的请求application/json

问问自己是否真的需要以这种方式发送 JSON 数据,而不是作为表单的一部分。

如果你这样做了,实现它的一种方法是使用 Javascript 将来自表单(或其他地方)的数据编译为 JSON,并生成一个XMLHttpRequest将其发布到你的服务器。

另一种不太理想的方法是删除对控制器方法的约束,使用 Autowired ObjectMapper 手动consumes将参数更改为并解析控制器方法中的响应。@RequestParam("obj") String objobjectMapper.readValue(obj, Employee.class)


推荐阅读