Table of Contents
@PathVariable和@RequestBody可以一起使用
@PathVariable和@RequestBody可以一起使用
1.@RequestMapping
@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有。
@Controller
//设置想要跳转的父路径
@RequestMapping(value = "/Controllers")
public class StatisticUserCtrl {
//如需注入,则写入需要注入的类
//@Autowired
// 设置方法下的子路经
@RequestMapping(value = "/method")
public String helloworld() {
return "helloWorld";
}
}
@PathVariable 注解,其用来获取请求路径(url )中的动态参数。
前段请求
function login() {
var url = "${pageContext.request.contextPath}/person/login/";
var query = $('#id').val() + '/' + $('#name').val() + '/' + $('#status').val();
url += query;
$.get(url, function(data) {
alert("id: " + data.id + "name: " + data.name + "status: "
+ data.status);
});
}
后端处理
/**
* @RequestMapping(value = "user/login/{id}/{name}/{status}") 中的 {id}/{name}/{status}
* 与 @PathVariable int id、@PathVariable String name、@PathVariable boolean status
* 一一对应,按名匹配。
*/
@RequestMapping(value = "user/login/{id}/{name}/{status}")
@ResponseBody
//@PathVariable注解下的数据类型均可用
public User login(@PathVariable int id, @PathVariable String name, @PathVariable boolean status) {
//返回一个User对象响应ajax的请求
return new User(id, name, status);
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------
@ResponseBody
@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
前段请求
function login() {
var datas = '{"username":"' + $('#username').val() + '","userid":"' + $('#userid').val() + '","status":"' + $('#status').val() + '"}';
$.ajax({
type : 'POST',
contentType : 'application/json',
url : "${pageContext.request.contextPath}/user/login",
processData : false,
dataType : 'json',
data : datas,
success : function(data) {
alert("userid: " + data.userid + "username: " + data.username + "status: "+ data.status);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("出现异常,异常信息:"+textStatus,"error");
}
});
};
后端处理
@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中,返回json对象响应回去
public User login(User user) {
User user = new User();
user .setUserid(1);
user .setUsername("MrF");
user .setStatus("1");
return user ;
}
异步获取 json 数据,加上 @Responsebody 注解后,就会直接返回 json 数据。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
2 @RequestBody
@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
使用时机:
A) GET、POST方式提时, 根据request header Content-Type的值来判断:
1.application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处 理,当然@RequestBody也能处理);
2.multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
3.其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
B) PUT方式提交时, 根据request header Content-Type的值来判断:
1 application/x-www-form-urlencoded, 必须;
2 multipart/form-data, 不能处理;
3 其他格式, 必须;
说明:request的body部分的数据编码格式由header部分的Content-Type指定
比如
@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中
public User login(@RequestBody User user) {
// 这样就不会再被解析为跳转路径,而是直接将user对象写入 HTTP 响应正文中
return user;
}
************************************************************************************************************************************
3 get post 获取参数
get与post两种方式的区别:对于本次主题而言,最显著的区别就是get请求方式参数是在url后,而post请求方式的参数是在request body中。因此两者获取参数的方式也大不一样。
1 Get方式参数的获取
直接在方法体中指定参数
@GetMapping("/get")
public User getUserById(Integer id) {
if (id.intValue() == 0) {
return null;
}
return list.get(id);
}
使用requestParam
@GetMapping("/get")
public User getUserById(@RequestParam(name = "id", required = true) Integer id) {
if (id.intValue() == 0) {
return null;
}
return list.get(id);
}
使用PathVariable
@GetMapping("/get/{id}")
public User getUserByPathValue(@PathVariable(name = "id", required = true) Integer id) {
return list.get(id);
}
使用HttpServletRequest
@GetMapping("/get")
public User getUserById(HttpServletRequest request) {
Integer id = Integer.parseInt(request.getParameter("id"));
if (id.intValue() == 0) {
return null;
}
return list.get(id);
}
2 POST方式参数的获取
一般而言,post形式的参数被放在请求体中以application/json的形式被后端获取
获取一个对象
@PostMapping("/save")
public User saveUser(@RequestBody User user) {
list.add(user);
return user;
}
使用Map
map中存放的键值对就对应于json中的键值对 content-type:application/json
@PostMapping("/save")
public User saveUser(@RequestBody Map<String, Object> map) {
Integer id = (Integer) map.get("id");
String name = (String) map.get("name");
Integer age = (Integer) map.get("age");
List<String> hobby=(List<String>) map.get("hobby");
User user = new User(id, name, age, hobby);
list.add(user);
return user;
}
使用HttpServletRequest
将content-type改为x-www-form-urlencoded
@PostMapping("/save")
public User save(HttpServletRequest request) {
Integer id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
Integer age = Integer.parseInt(request.getParameter("age"));
String parameter = request.getParameter("hobby");
User user = new User(id, name, age, null);
list.add(user);
return user;
}
通过HTTP协议将参数转换为JSONObject
@PostMapping("/save")
public User save(HttpServletRequest request) throws IOException, JSONException {
JSONObject jsonObject = handlerData(request);
Integer id = jsonObject.getInteger("id");
String name = jsonObject.getString("name");
Integer age = jsonObject.getInteger("age");
List<String> hobby = jsonObject.getObject("hobby", List.class);
User user = new User(id, name, age, hobby);
list.add(user);
return user;
}
//这里使用的是alibaba的json工具类
public static JSONObject handlerData(HttpServletRequest request) throws IOException, JSONException {
StringBuffer sb = new StringBuffer();
InputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
if (sb.toString().length() <= 0) {
return null;
} else {
return JSONObject.parseObject(sb.toString());
}
}
直接使用参数
说明直接使用username为参数可以接受,直接使用类也可以接受。
// 获取post请求参数(直接使用参数)
@RequestMapping(value="saveUser2", method=RequestMethod.POST)
public String saveUser2(String username, User user){
System.out.println("username - " + username);
System.out.println("user.username - " + user.getUsername());
return "login/welcome";
}
@PostMapping("/doAssign") public R doAssign(String id,String[] permissionIds) { log.info("doAssign()**********id:{},permisionIds:{}",id,permissionIds); Boolean flag = aclPermissionService.doAssign(id,permissionIds); if(flag){ return R.ok().message("分配菜单成功"); }else { return R.error().message("分配菜单失败"); } }