@RequestBody/@ResponseBody/@RequestParam
小白-----记录点点滴滴
先简单介绍一下@RequestMapping
1、功能简介
@RequestMapping(“url”)
单独使用是一个跳转页面url的注解(最浅显的一种理解)
示例:POST方式跳转
@RequestMapping(value=”/test”,RequestMethod=RequestMethod.POST
)
简写 @PostMapping(“/test”)
示例:GET方式跳转
@RequestMapping(value=”/test”,RequestMethod=RequestMethod.GET
)
简写 @GetMapping(“/test”)
2、示例
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
//重载路径,一般是return "appointments";
return "redirect:/appointments";
}
@RequestBody
@RequestBody是作用在形参列表上,用于将前台发送过来固定格式的数据【xml 格式或者 json等】封装为对应的 JavaBean 对象,封装时使用到的一个对象是系统默认配置的 HttpMessageConverter进行解析,然后封装到形参上
示例:
@RequestMapping("/login.do")
@ResponseBody
public Object login(@RequestBody User loginUuser, HttpSession session) {
user = userService.checkLogin(loginUser);
session.setAttribute("user", user);
return new JsonResult(user);
}
对应的jquery的写法有:
function lg(){
var loginUuser={};//字面量创建对象
loginUuser.name="xw";
loginUuser.age="35";
loginUuser.sex="男";
$.ajax({
type: "POST",
url: "rest/officeNotice/addOffice",
dataType: "json",
contentType: 'application/json;charset=utf-8', //设置请求头信息
data: JSON.stringify(loginUuser),
//data: {"data": JSON.stringify(SearchFaOffice)},
success: function (res) {
if (res.code) {
layer.msg('提交成功', {time: 2000}, function () {
window.parent.tableIns.reload();//刷新父页面
var index = parent.layer.getFrameIndex(window.name);//获取当前弹出层的层级
parent.layer.close(index);//关闭弹出层
});
} else {
layer.msg(res.msg, {time: 2000, icon: 2});
}
}
});
}
}
注意:
contentType: ‘application/json;charset=utf-8’, //设置请求头信息
data: JSON.stringify(loginUuser), //将js的json对象转json字符串
contentType 主要设置你发送给服务器的格式,dataType设置你收到服务器数据的格式
在 jquery 的 ajax 中, contentType都是默认的值:application/x-www-form-urlencoded
contentType默认的,可以传简单的对象如:
var jd={
a: 1,
b: 2,
c: 3
}
但是复杂的不可以传,
例如在 ajax 中你要传一个复杂的 json 对像,也就说是对象嵌数组,数组中包括对象,如果你这样传:
var fz={
data: {
a: [{
x: 2
}]
}
}
这个复杂对象, application/x-www-form-urlencoded 这种形式是没有办法将复杂的 JSON 组织成键值对形式(当然也有方案这点可以参考 ) ,你传进去可以发送请求,但是服务端收到数据为空, 因为 ajax 没有办法知道怎样处理这个数据。这里就可以使用上面自定义contentType为json字符串,将准备传入的复杂对象童年过JSON.stringify(fz)为字符串进行传参
在上面的例子中:loginUuser对象为简单的对象所以可以去掉contentType的自定义设置,使用默认的设置,data:loginUuser即可
@ResponseBody
@ResponseBody是作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。@RequestBody 将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
示例:
function loginAction() {
// 获取用户输入的账号和密码
var name = $('#count').val();
var password = $('#password').val();
$.ajax({
url : 'account/login.do',
type : 'post',
// data对象中的属性名要和服务端控制器的参数名一致 login(name, password)
data : {
'name' : name,
'password' : password
},
dataType : 'json',
success : function(result) {
if (result.state == 0) {
// 登录成功,设置cookie并跳转edit.html
addCookie('userId', result.data.id);
addCookie('nick', result.data.nick);
location.href = 'edit.html';
} else {
// 登录失败
var msg = result.message;
$('#sig_in').next().html(msg);
$('#sig_in').next().css("color", "red");
}
},
error : function(e) {
alert("系统异常");
}
});
$('#password').val("");
}
@RequestMapping("/login.do")
@ResponseBody
public Object login(String name, String password, HttpSession session) {
user = userService.checkLogin(name, password);
session.setAttribute("user", user);
return new JsonResult(user);
}
@RequestParam
1、可以对传入参数指定参数名
//不通过value指定前端的参数名,则前段必须与参数名相同,如下前端需要传inputStr参数名
1 @RequestParam String inputStr
// 下面的对传入参数指定为aa,如果前端不传aa参数名,会报错
2 @RequestParam(value=“aa”) String inputStr
2、可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传
1 // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有
2 @RequestMapping("testRequestParam")
3 public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)
3、如果@requestParam注解的参数是int类型,并且required=false,此时如果不传参数的话,会报错。原因是,required=false时,不传参数的话,会给参数赋值null,这样就会把null赋值给了int,因此会报错。
1 // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有
2 @RequestMapping(“testRequestParam”)
3 public String filesUpload(@RequestParam(value=“aa”, required=false) int inputStr, HttpServletRequest request)
4 若是前端页面不传参的话,此处就会报错。当然可以用Integer代替int
@RequestBody封装实体参数,@RequestParam是单个参数
@PathVariable
@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值
1、与@RequestParam的区别
在spring MVC中,两者的作用都是将request里的参数的值绑定到contorl里的方法参数里的,区别在于,URL写法不同。
使用@RequestParam时,URL是这样的:http://host:port/path?参数名=参数值
使用@PathVariable时,URL是这样的:http://host:port/path/参数值
2、
@PathVariable(“xxx”)
通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/hello/show5/1/james
package com.day01springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
/**
* @ Author :ShaoWei Sun.
* @ Date :Created in 20:58 2018/11/16
*/
@Controller
@RequestMapping("hello")
public class HelloController2 {
/**
*3、占位符映射
* 语法:@RequestMapping(value=”user/{userId}/{userName}”)
* 请求路径:http://localhost:8080/hello/show5/1/james
* @param ids
* @param names
* @return
*/
@RequestMapping("show5/{id}/{name}")
public ModelAndView test5(@PathVariable("id") Long ids ,@PathVariable("name") String names){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","占位符映射:id:"+ids+";name:"+names);
mv.setViewName("hello2");
return mv;
}
}
@RequestMapping中有的参数名称方法中可以没有,但是方法中有的参数名称@RequestMapping一定要有。
{name}对应的@PathVariable(name = “name”)中的"name",如果参数String name与地址中{name}名称相同
那么@PathVariable(name = “name”)可以忽略name属性
@PathVariable 属性name与value功能相同
@PathParam
同@PathVariable一样也是从url取参数值,但是采用的是传统的url?a=1&b=2。
不同的是@PathVariab在没有对应属性时会是一个null值,不会报错。
通过访问地址:http://127.0.0.1:8080/test/add?a=1&b=2
得到的输出结果是 1 、2
@RestController
@RequestMapping(value = "/{test}")
public class ChineseDrugController {
@ResponseBody
@RequestMapping(value = "/{add}")
public String showName(@PathParam(value = "a") int a, @PathParam(value = "b") int b) {
return a+"、"+b;
}
}
本文章是我学习前辈们的知识,在这里整理一下,怕自已忘记了,方便下次学习用,只是我的学习笔记…哈