@RequestParam,@PathVariable,@ResponseBody,@RequestBody,@ModelAttribute学习

一、@RequestParam使用于参数上,用于将请求参数映射到指定参数变量上html

例如:ajax

1 @RequestMapping(value="/hello",method=RequestMethod.GET) 2 
3 public String testPara(@RequestParam String str){ 4 
5 System.out.println(str); 6 
7 return "hello"; 8 
9 }

当咱们访问 http://localhost:8080/springMVC/hello?str=xx 的时候,会将xx注入到testParam方法中的str中,你会看到输出xxspring

固然此时你在浏览器的参数名称必须跟testPara中的参数同样即必须都为str,假如你想使用不一样的参数名称,就必须在@RequestParam(" anothername") str 指定json

参数名,这样当你访问 http://localhost:8080/springMVC/hello?anothername=xx ,就会将xx注入到str中了。springMVC中默认就是开启 @RequestParam功能的,浏览器

你直接访问http://localhost:8080/springMVC/hello?str=xx在程序中不写@RequestParam,仍是会注入到str参数中。固然咱们最好仍是写一下,有助于理解和利于服务器

代码的阅读 app

二、@PathVariable与@RequestParam相似,可是它是用于rest风格 访问时候获取参数的方式,使用这个注解前提是在@RequestMapping中必须指定模板,否则异步

访问可能出现400,服务器不懂你要干吗。例以下面的例子:jsp

 1 public String testPath(@PathVariable String para)  2 
 3 @RequestMapping(value="/hello/{para}",method=RequestMethod.GET) //在reqestMapping指定了模板{para}
 4 
 5 public String testPath(@PathVariable String para){  //参数名字必定要跟模板的名字同样,若是不想跟模板同样,能够写成这样@PathVariable("para")String other
 6 
 7 System.out.println(para);  8 
 9 return "hello"; 10 
11 }

访问:http://localhost:8080/springMv/spring/hello/anty    控制台输出参数anty async

三、 @responsebody表示该方法的返回结果直接写入HTTP response body中
通常在异步获取数据时使用,在使用@RequestMapping后,返回值一般解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中响应给客户端。好比异步获取json数据,加上@responsebody后,会直接返回json数据。使用时机:返回的数据不是html标签的页面,而是其余某种格式的数据时(如json、xml等)使用;

例如如下代码:

服务器端:

 1 @RequestMapping(value="/ajaxRequest")  2 
 3 @ResponseBody  4 
 5 public String ajax(String str){  6 
 7 str="sb";  8 
 9 return str; 10 
11 }

 客户端代码:

         $.ajax({

           type:"POST",

            async : false,

            url:"spring/ajaxRequest",

            success:function(data){

            alert(data);               

            } 

});

点击页面按钮访问服务器,弹出sb 

四、@RequestBody

做用: 

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,而后把相应的数据绑定到要返回的对象上;

      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

·     application/x-www-form-urlencoded, 可选(即非必须,由于这种状况的数据@RequestParam, @ModelAttribute也能够处理,固然@RequestBody也能处理);

·     multipart/form-data, 不能处理(即便用@RequestBody不能处理这种格式的数据);

·     其余格式, 必须(其余格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

B) PUT方式提交时, 根据request header Content-Type的值来判断:

·     application/x-www-form-urlencoded, 必须;

·     multipart/form-data, 不能处理;

·     其余格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;m 

requestbody能够直接将客户端发来的ajax请求的json对象注入到服务端的对象中,可是json对象的字段必须跟后台对象的字段对应,

例如 var user{"username":"tom"} 后台的User对象必需要有username 这个字段。既然是使用异步,那么requestBody不少时候是跟responseBody搭配着一块儿使用!!例以下列代码:

//@RequestMapping(value="/ajaxRequest")

//@ResponseBody

//public String ajax(@RequestBody User user){

//System.out.println(user.getUsername());

//return user.getUsername();

//}

客户端代码:

  var m = { 

                "username":'fuckyou'

            };

        $.ajax({

            type:"POST",

            async : false,

            url:"spring/ajaxRequest",

            dataType:"json",

            contentType:"application/json; charset=utf-8",//必定要加这一句发送内容为json

            data:JSON.stringify(m),//requestbody接收的是json字符串,因此得将json对象进行转换不然报415错误类型没法识别

            success:function(data){

                alert("return map success!");               

            }

});

在客户端发起请求,服务器控制台输出fuckyou,表示username字段注入到user对象 

五、@ModelAttribute    一种是放在方法上面,一种是放在参数上面(比较经常使用的是放在参数前面)

放在方法上面:

 1  @ModelAttribute  2     public User User(User userd){  3         userd.setUsername("fuckg");  4         return userd;  5         
 6  }  7     @RequestMapping(value="/hello",method=RequestMethod.GET)  8     public String testPara(User u){  9  System.out.println(u.getUsername()); 10         return "hello"; 11     }

在到达全部requestMapping以前 会被modelAttribute拦截,在客户端提交表单 会将对应 的属性 注入到Userd 对象中,而后springMVC默认会将usrerd对象 放入视图中,以便访问, 咱们能够在hello页面 使用{user.username} 访问,

这里要注意的是 无论参数是写成userd仍是写成users,都只能经过user.username访问到,spring是按照该对象类型 的小写来访问,User类对象,因此在页面就经过user访问属性。 

第二种是将注解放到参数前:

1 @RequestMapping("/modd") //默认使用modelAttribute,若是去掉效果仍是同样
2     public String testModelAttr(@ModelAttribute User userqqq){ 3  System.out.println(userqqq.getUsername()); 4         return "md"; 5         
6     }
 

这里也是表单提交过来的参数 会注入到user 对象的对应属性上(这里表单提交过来的数据,不能使用@RequestBody替换ModelAttribute,requestBody经常使用在异步提交json数据,在这换成requestBody的话会报415错误),而后spring 也会把该对象放入视图中,在md.jsp页面,就能够经过${user.username}访问,固然这里也是同样 

无论参数写成什么样,仍是按照该类型的小写字母来访问,因此不是按userqqq来访问,直接按照User-->小写user访问。

尝试了一下去除ModelAttribute的效果,发现仍是可用,说明,是spring 默认开启了参数前 的ModelAttribute注解,不过要用的时候仍是写出来 利于代码阅读 

@requestBody 和@ModelAttribute 均可以用来绑定请求数据到参数上,在个人理解范围内:requestBody主要是将异步请求ajax,json字符串绑定到对象上,requestBody

只接受json字符串,因此记得使用JSON.stringif方法将json对象转成字符串,  而ModelAttribute主要接收来自表单或者url?para参数,将参数绑定到对象上。

转自:https://blog.csdn.net/zz210891470/article/details/59719251