SpringMVC-接收参数的集中方式

一、直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交。

1:直接把表单的参数写在Controller相应的方法的形参中(入参名称一致)
@RequestMapping("/requestParam")
public String addUser1(String username,String password) {
System.out.println("username is:"+username);
     System.out.println("password is:"+password);
     return "demo/index";
}
2:入参名称不一致 
当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,

例如: @RequestParam(value="a", required=false)

@RequestMapping(value = "/requestParam", method = RequestMethod.GET) 
public String setupForm(@RequestParam("a") String username,String passwsord) { 
    System.out.println(username); 
return "helloWorld";
}
url形式:http://localhost/requestParam?username=lixiaoxi&password=111111

二、通过HttpServletRequest接收,post方式和get方式都可以 

三、通过@PathVariable获取路径中的参数

url:http://localhost/SSMDemo/demo/addUser4/123/lisi

@RequestMapping(value="user/{id}/{name}",method=RequestMethod.GET)
public String printMessage1(@PathVariable String id,@PathVariable String name) {
        
      System.out.println(id);
      System.out.println(name);
      return "users";
}

三、当请求参数过多时,以对象的方式传递:通过一个bean来接收,post方式和get方式都可以 需要添加jackson依赖

注意:参数是Json格式、需要使用注解:@RequestBody
在上代码之前,有必要先说说@RequestBody注解的含义:
用该注解标识的方法的参数,会和web请求体绑定。
http消息转换器会根据content-type的设置将请求体解析,从而初始化该方法的参数。
"Content-Type"的值设置为:"application/json"

猜你喜欢

转载自www.cnblogs.com/lyx-2018-yh-qingliu/p/10418261.html