• ajax post请求request.getParameter("")取值为null


    今天在写提交一个json数据到后台,然后后台返回一个json数据类型。但是发现后台通过request.getParamter(“”)取到的值为null。

    于是写一个简单的ajax 请求,来排查问题
    前台代码:

    $(document).ready(function(){
        $("#ajax").click(function(){
            var depart="depart";
            $.ajax({
                url :path+ "/AjaxReponse",
                data :"depart="+depart,
                type : "post",
                dataType : "json",      
                success: function(data){
                    alert(data);
                }
            });
        });
    });

    后台代码:

    String depart=request.getParameter("depart");

    现象:后台取到值为null。但是在google chrome调试工具调试时,request中已经有发送的值了
    这里写图片描述

    一.网友方法

    正常的post请求(不包括ajax请求)在http头中的content-type为application/x-www-form-urlencoded,这时在java后台可以通过request.getParameter(name)的形式获取.但是通过原生ajax请求时,在java后台通过request.getParameter(name)的形式却无法获取到传入的参数.
    但是实际上在上图中可以看到,content-type已经是application/x-www-form-urlencoded的形式了。所以网友的方法不适用
    http://m.blog.csdn.net/blog/eyebrother/36007145

    二.编码格式
    既然在调试器中看到request的发送内容没问题,那么就是编码格式的问题了。在后台添加代码:
    request.setCharacterEncoding(“utf-8”);
    可以解决这个问题。
    但是发现前台写成这种类型

        data :{
                    "depart" : depart
                },

    后台取到的也是null。所以最终将js文件编码格式改为utf-8.解决这个问题

    三.发送json类型数据到后台

    $(document).ready(function(){
        $("#ajax").click(function(){
            var isReceipt = "1";
            var adress ="2";
            var reason = "3";
            var projectInfo = {
                    "adress" : isReceipt,
                    "ownerDept" : {
                        "deptCode" : adress
                },      
                "reason" : reason
            };
            $.ajax({
                url :path+ "/AjaxReponse",
                data :{
                    "depart" : JSON.stringify(projectInfo)
                },
                type : "post",
                dataType : "json",      
                success: function(data){
                    alert(data);
                }
            });
        });
    });

    后台:

    String depart=request.getParameter("depart");
    Gson gson = new GsonBuilder().create();
    Depart dep = gson.fromJson(depart),
            Depart.class);

    前台通过JSON.stringify()方法将json类型转换为string类型发送。
    后台是使用google的GSON包,然后将json类型数据(String)转换为实体类数据类型。

    四.js 工具
    由于js语法比较复杂,编译器无法进行检查。所以js代码风格,错误比较难找。这里推荐我使用的两个工具。
    1. JSTool
    可以格式化js代码
    2. JSLINT
    检查语法错误
    具体使用不详述了,我都是下载这两个工具对应的notepad++插件。在notepad使用非常方便。

    五. 吐槽
    csdn 的新版博客编辑器确实不错,但是在写博客时没有随手保存,打开其他的csdn页面时,提示markdown 编辑器实例已运行,必须重写加载。然后整篇博客都重写了。实在是不能忍!

  • 相关阅读:
    python接口测试3-JSON格式
    python接口测试2-开发WEB接口
    接口测试1-基础
    Apifox接口测试管理工具
    python的pip安装超时问题解决
    ubuntu解决安装速度问题
    vim进入粘贴模式
    禅道数据库
    内存管理
    文件操作
  • 原文地址:https://www.cnblogs.com/stoneFang/p/6715312.html
Copyright © 2020-2023  润新知