Content type 'application/json;charset=UTF-8' not supported

今天敲了一下springmvc框架的@RequestBody和@ResponseBody处理ajax请求,但是遇到了一点问题,特来记录一下.

$("#btn").click(function(){
			/*-------ajax代码-------*/
			$.ajax({
				type:"post",
				url:"${pageContext.request.contextPath}/JsonAA.action",
				// 设置请求头的数据类型
				contentType:'application/json;charset=utf-8',
				//接收服务器响应的数据类型
                dateType:"json",
				//请求的参数(json串)
				data:JSON.stringify({"username":"朱茵","password":'123'}),
				//回调函数
				success:function(data){
					alert(data.username);
				},error: function(obj){
			         alert("操作出错");
			         return false;
			     }
			});
		});
@Controller
public class UserController {

	@RequestMapping("/JsonAA")
	@ResponseBody
	public User ajax_json(@RequestBody User user) {
		System.out.println(user);
		return user;
	}
}

启动tomcat,打开网页,点击按钮,哦豁…
无任何显示,然后调试页面,查看控制台,Http请求返回415错误码

jquery-1.12.4.js:10254 POST http://localhost:7587/2020-2-6/JsonAA.action 415 (Unsupported Media Type)

415错误我们先查看contentType的值是否为application/json;charset=utf-8
检查了请求头无误
我们再查看User实体类中的getter,setter方法是否写错完了

public class User {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + "]";
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
}

并没有任何问题,执行了4,5次测试后,我打开springmvc的核心配置文件中,我并未配置 标签,加上之后,成功显示!!

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!--开启包扫描-->
	<context:component-scan base-package="cn.cg.controller"/>
	
</beans>

总结:
415错误码原因:
1.请求头的contentType属性的值是否为"application/json"
2.bean实体类中的getter,setter方法是否正确
3.标签

(标签会自动注册处理器映射器(RequestMappingHandlerMapping)处理器适配器(RequestMappingHandlerAdapter)异常处理器(HandlerExceptionResolver)
,控制器通过@Controller注解被容器扫描到,@RequestMapping注解将请求的URL映射到类的方法上,没有改标签否则它只不过是个普通bean类,)

你可能感兴趣的:(Content type 'application/json;charset=UTF-8' not supported)