ajax的post请求提交的数据在后端无法用request.getParameter获取的原因分析

前台JS请求代码demo

注意下方http请求的content-type是application/json

var _phoneId = "123456789";

var closeUrl=contextPath+"/close";

ajax(closeUrl,{
    
    "phoneId":_phoneId},"post",false,callbackForSessionClose,null,'json');

function ajax(url,reqData,type,async,successBack,errorBack,statusText,dataType){
    
    

    $.ajax({
    
    
        type : type,
        url : url,
        dataType : dataType,
        async : async,
        timeout : "60000",
        contentType : "application/json",
        data : JSON.stringify(reqData),
        success : function(data) {
    
    
            // 成功的处理逻辑

        },
        error : function(data) {
    
    
            // 错误的处理逻辑
        }

    });
}

后台接收请求数据代码

@RequestMapping(value="/close",method=RequestMethod.POST)
@ResponseBody
public String closeSession(HttpServletRequest request){
    
    
    String response;
    try{
    
    
        String phoneId = request.getParameter("phoneId");
        if(phoneId == "123456789"){
    
    
            response = "success";
        }else{
    
    
            response = "error";
        }
    }catch (ServiceException e) {
    
    
        //业务异常处理逻辑
    }catch (Exception e) {
    
    
        //非业务异常处理逻辑

    }
    return response;
}

原因分析

原因是原生ajax请求时,在http头中的content-typetext/plain;charset=UTF-8.当请求到达tomcat服务器时,服务器只对application/x-www-form-urlencoded形式的http,post请求进行读取body体中的参数,并放到request的parameter中,对于原生ajax请求则直接忽略,不会读取body体中的参数,才导致request.getParameter(name)读取不到参数.

再进一步查看tomcat中的代码
Tomcat的HttpServletRequest类的实现类为org.apache.catalina.connector.Request(实际上是org.apache.coyote.Request)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43944305/article/details/109615171