springmvc请求接收参数的几种方法 js传递数组到后台

参考:https://blog.csdn.net/yaerfeng/article/details/23658391

https://blog.csdn.net/bincain1993/article/details/78286327

https://blog.csdn.net/zhaohuijiadelu/article/details/54408324

很惭愧用了spring这么多年,总是弄混接收参数的几个注解

通过@PathVariabl注解获取路径中传递参数

转载请注明出处:springmvc请求接收参数的几种方法

代码下载地址:http://www.zuidaima.com/share/1751862044773376.htm

JAVA

[java]  view plain  copy
  1. @RequestMapping(value= " /{id}/{str} " )  
  2.  public ModelAndView helloWorld(@PathVariable String id, @PathVariable String str) {  
  3.  System.out.println(id);  
  4.  System.out.println(str);  
  5.  return new ModelAndView( " /helloWorld " );  
  6. }  

 


用@ModelAttribute注解获取POST请求的FORM表单数据
JSP

 

 

[java]  view plain  copy
  1. <form method="post" action="hao.do">  
  2.  a: <input id="a" type="text" name="a"/>   
  3.  b: <input id="b" type="text" name="b"/>   
  4.  <input type="submit" value="Submit" />   
  5.  </form>  

 


JAVA pojo

 

 

[java]  view plain  copy
  1. public class Pojo{  
  2. private String a;  
  3. private int b;  

 


JAVA controller

 

 

[java]  view plain  copy
  1. @RequestMapping(method= RequestMethod.POST)  
  2.  public String processSubmit(@ModelAttribute" pojo " ) Pojo pojo) {  
  3.  return " helloWorld " ;  
  4.  }  

 


直接用HttpServletRequest获取
JAVA

 

 

[java]  view plain  copy
  1. @RequestMapping(method= RequestMethod.GET)  
  2.  public String get(HttpServletRequest request, HttpServletResponse response) {  
  3.  System.out.println(request.getParameter( " a " ));  
  4.  return " helloWorld " ;  
  5. }  

 


用注解@RequestParam绑定请求参数a到变量a
当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,
例如: @RequestParam(value="a", required=false)
JAVA

 

 

 

[java]  view plain  copy
  1. @RequestMapping(value= " /requestParam " , method= RequestMethod.GET)  
  2.  public String setupForm(@RequestParam" a " ) String a, ModelMap model) {  
  3.  System.out.println(a);  
  4.  return " helloWorld " ;}   
pringMVC项目中,后台Java方法使用注解获取参数,ajax请求时分两种情况  {
    1:后台使用@requestParam  
    2:后台使用@requestBody时
}
1:后台使用@RequestBody需要注意的是: 
    1》:ajax中参数需要将json对象转成json格式的字符串
    2》:contentType需要设置成 application/json;



function testAjax() {
    var url = "/agentmobileApp/test/testRequestBody";
    var reqPara = JSON.stringify({'did': '55', 'name': 'jack', 'age': 15});
    $.ajax({
        async: false,
        url: url,
        type: 'POST',
        timeout: '30000',
        data: reqPara,
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        success: function (rep) {
            alert(rep.result + " ;" + rep.message + " ;" + rep.data.resp.name);
        },
        error: function (rep) {
            alert("请检查网络是否连接" + rep);
        }
    });
}
java端代码:
@RequestMapping("/testRequestBody")
//@RequestMapping(value = "/testRequestBody",method = {RequestMethod.POST})
@ResponseBody
public ResultJson testResponseBody(@RequestBody BodyVO bodyVO) {
    ResultJson resultJson = new ResultJson();
    TestVO testVO = new TestVO();

    String did = bodyVO.getDid();
    String name = bodyVO.getName();
    int age = bodyVO.getAge();
    logger.info("获取前端的参数did :" + did + " name: " + name + "  age: " + age);
    // 简单组装参数
    testVO.setAge(20);
    testVO.setName(did);
    testVO.setAddress(did + "66666");

    resultJson.setResult("0000");
    resultJson.setMessage("成功了啊");
    resultJson.getData().put("resp", testVO);
    return resultJson;
}
 
 
 
 
2:后台使用@requestParam时
        需要注意的是:
        1》:参数为json对象
        2》:contentType 选项需要注释掉

 
 
function testAjax1() {
    var url = "/agentmobileApp/test1/testResponseBody";
    var reqPara = {'did': '555', 'name': 'jack', 'age': 15};
    $.ajax({
        async: false, 
        url: url, 
        type: 'POST', 
        timeout: '30000', 
        data: reqPara,
        //contentType: 'application/json;charset=utf-8', 
        dataType: 'json', 
        success: function (rep) {
            alert(rep.result + " ;" + rep.message + " ;" + rep.data.resp.name);
        }, error: function (rep) {
            alert("请检查网络是否连接" + rep);
        }
    });
}

JAVA端:
@RequestMapping("/testResponseBody")
@ResponseBody
public ResultJson testResponseBody(@RequestParam String did, @RequestParam String name, @RequestParam int age) {
    ResultJson resultJson = new ResultJson();
    TestVO testVO = new TestVO();

    testVO.setAge(20);
    testVO.setName(did);
    testVO.setAddress(did + "66666");
    resultJson.setResult("0000");
    resultJson.setMessage("成功了");
    resultJson.getData().put("resp", testVO);
    return resultJson;
}

js传递数组到后台

方法一: 
1.使用JSON.stringify 将数组对象转化成json字符串;

var array = ["1", "2"];
$.ajax({  
    type : 'POST',  
    url: path + '/check/testPost',  
    contentType : "application/json" ,
    data : JSON.stringify(array), 
    success : function(data) {  

    }  
}); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.传输过程中参数 
这里写图片描述

3.后台处理

@RequestMapping(value = "/testPost", method = {RequestMethod.POST})
public void testPost(@RequestBody String[] array) throws IOException {
    for (String string : array) {
        System.out.println(string);
    }
    return ;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

方法二: 
1.前端不做处理:

var array = ["1", "2"];
$.ajax({  
    type : 'POST',  
    url: path + '/check/testPost',
    contentType: "application/x-www-form-urlencoded",
    data: {"array": array},
    success : function(data) {  
    }  
});  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.传输过程中参数 
这里写图片描述

3.后台处理

@RequestMapping(value = "/testPost", method = {RequestMethod.POST})
public void testPost(HttpServletRequest req) throws IOException {
    String[] array = req.getParameterValues("array[]");
    for (String string : array) {
        System.out.println(string);
    }
    return ;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注:两种post请求的content-type不同。



猜你喜欢

转载自blog.csdn.net/liwenxia626/article/details/80784350
今日推荐