文章目录
一、在Controller中增加方法,处理GET及POST类型的请求
1.1GET请求
当数据格式为这样子:/students?current=1&limit=5
处理请求代码如下:
@RequestParam注解
// /students?current=1&limit=5
@RequestMapping(path = "/students",method = RequestMethod.GET)
@ResponseBody
public String getStudents(
@RequestParam(name = "current",required = false,defaultValue = "1") int current,
@RequestParam(name = "limit",required = false,defaultValue = "10")int limit){
System.out.println(current);
System.out.println(limit);
return "some students";
}
运行结果如下:
当数据格式为这样子:/student/{id}
处理请求代码如下:
@PathVariable注解
// /student/{id}
@RequestMapping(path = "/student/{id}",method = RequestMethod.GET)
@ResponseBody
public String getAStudent(@PathVariable("id") int id){
System.out.println(id);
return "bwy";
}
运行结果如下:
1.2POST请求
网页把信息传回给服务器
+html联合使用
@RequestMapping(path = "/student",method = RequestMethod.POST)
@ResponseBody
public String saveTeacher(String name,int age) {
System.out.println(name);
System.out.println(age);
return name;
}
二、在Controller中增加方法,向浏览器响应HTML格式的数据
//响应HTML数据
@RequestMapping(path = "/teacher",method = RequestMethod.GET)
public ModelAndView getTeacher(){ //mode数据和视图相关数据
ModelAndView mv = new ModelAndView();
mv.addObject("name","baibweyab ");
mv.addObject("age",30);
mv.setViewName("/demo/view");
return mv;
}
view.html位于templates/demo目录下
<!DOCTYPE html>
<html lang="en" xmlns:th = "http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Teacher</title>
</head>
<body>
<p th:text="${name}"></p>
<p th:text="${age}"></p>
</body>
</html>
运行结果如下:
响应HTML数据(优化):
//响应HTML数据(优化)
@RequestMapping(path = "/school",method = RequestMethod.GET)
public String getSchool(Model model){
model.addAttribute("name","西北大学");
model.addAttribute("age",121);
return "/demo/view";
}
三、在Controller中增加方法,向浏览器响应JSON格式的数据
//当前网页不动,当前网页不刷新,但已经悄悄进行了一次请求 JSON
//响应JSON数据(异步请求)
@RequestMapping(path = "/emp",method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> getEmp(){
Map<String,Object> map = new HashMap<>();
map.put("name","zhangsan");
map.put("age",23);
map.put("salsry",8000);
return map;
}
运行结果如下:
当处理多条记录时:
@RequestMapping(path = "/emps",method = RequestMethod.GET)
@ResponseBody
public List<Map<String,Object>> getEmps(){
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> map = new HashMap<>();
map.put("name","zhangsan");
map.put("age",23);
map.put("salsry",8000);
Map<String,Object> map2 = new HashMap<>();
map2.put("name","zhangsansan");
map2.put("age",28);
map2.put("salsry",10000);
list.add(map);
list.add(map2);
return list;
}
运行结果如下: