当数据格式为这样子:/students?current=1&limit=5
处理请求代码如下:
@RequestParam注解
// /students?current=1&limit=5@RequestMapping(path = "/students",method = RequestMethod.GET)@ResponseBodypublic 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)@ResponseBodypublic String getAStudent(@PathVariable("id") int id){System.out.println(id);return "bwy";}
运行结果如下:
网页把信息传回给服务器
+html联合使用
@RequestMapping(path = "/student",method = RequestMethod.POST)@ResponseBodypublic String saveTeacher(String name,int age) {System.out.println(name);System.out.println(age);return name;}
//响应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目录下
Teacher
运行结果如下:
响应HTML数据(优化):
//响应HTML数据(优化)@RequestMapping(path = "/school",method = RequestMethod.GET)public String getSchool(Model model){model.addAttribute("name","西北大学");model.addAttribute("age",121);return "/demo/view";}
//当前网页不动,当前网页不刷新,但已经悄悄进行了一次请求 JSON//响应JSON数据(异步请求)@RequestMapping(path = "/emp",method = RequestMethod.GET)@ResponseBodypublic Map getEmp(){Map map = new HashMap<>();map.put("name","zhangsan");map.put("age",23);map.put("salsry",8000);return map;}
运行结果如下:
当处理多条记录时:
@RequestMapping(path = "/emps",method = RequestMethod.GET)@ResponseBodypublic List
运行结果如下: