json - 为什么我在 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;
}
}
解决方案
您将获得 415 状态,因为您的浏览器正在向application/x-www-form-urlencoded
仅接受的控制器方法发送内容类型为 的请求application/json
。
问问自己是否真的需要以这种方式发送 JSON 数据,而不是作为表单的一部分。
如果你这样做了,实现它的一种方法是使用 Javascript 将来自表单(或其他地方)的数据编译为 JSON,并生成一个XMLHttpRequest将其发布到你的服务器。
另一种不太理想的方法是删除对控制器方法的约束,使用 Autowired ObjectMapper 手动consumes
将参数更改为并解析控制器方法中的响应。@RequestParam("obj") String obj
objectMapper.readValue(obj, Employee.class)
推荐阅读
- javascript - 如果 React 组件的 props 更新但值没有改变,它会重新渲染吗?
- python - SQL 查询的值部分中的占位符错误
- php - 无法测试数组元素的值,但可以打印它
- angularjs - 如何在 Y 轴上呈现,格式 hh: mm: ss Chart.js
- internet-explorer - 仅在 IE 中出现 Recaptcha v2 错误。'MessageChannel' 未定义
- php - Symfony 表单重定向到控制器而不是路由
- bash - 带有函数 / for 循环的 Bash Scipt
- php - S3 Flysystem 返回文件密钥,但 size 方法抛出“未找到”
- pywinauto - 让 pywinauto 在截屏前运行所有的 cmd 命令
- jquery - 现有 JS 的 Google Analytics 问题