@RequestBody接收json对象报415的解决办法

前端请求:

$.ajax({
            url: basePath() + "/index/login.do",
            type : "post",
            data: JSON.stringify(form),
            dataType : "json",
            contentType : "application/json;charset=utf8",
            success: function (data) {
                console.log(data);
            },
            error: function () {

            }
        });

后端接收:

@ResponseBody
	@RequestMapping(value = "/login",method = RequestMethod.POST,produces = "application/json;charset=utf8")
	public JSONObject login(@RequestBody LoginVo loginVo){

		JSONObject result = new JSONObject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword());
		System.out.println(loginVo.isRememberMe());
		Subject subject = SecurityUtils.getSubject();
		subject.login(token);
		if (subject.isAuthenticated()){
			result.put("result",true);
		}else{
			result.put("result",false);
		}
		return result;
	}

前端ajax请求,后端使用@RequestBody接收,报出415请求数据格式错误

错误原因:springMVC无法读取ajax设置好的dataType并以对应的方式处理请求头,进而无法处理json数据

解决办法:在maven中引入Jackson相关jar包,并在springMVC的xml中引入相关配置,maven和springMVC的相关代码如下:

maven:


            com.fasterxml.jackson.core
            jackson-databind
            2.9.6
        

        
            com.fasterxml.jackson.core
            jackson-core
            2.9.6
        

        
            com.fasterxml.jackson.core
            jackson-annotations
            2.9.6
        

springMVC:


    
        
            
                
                
                    
                        
                            text/html;charset=UTF-8
                            application/json;charset=UTF-8
                        
                    
                
                
                
                    
                        
                            text/html;charset=UTF-8
                            application/json;charset=UTF-8
                        
                    
                
            
        
    

 

你可能感兴趣的:(spring)