(一)两种传参方法:
1.地址栏 ?current=1&limit=1 形式:
——@RequestParam(非必需)
@RequestMapping("students")
@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 student";
}
2.地址栏 /123 形式
@RequestMapping(path = "/student/{id}",method = RequestMethod.GET)
@ResponseBody
public String getAStudent(@PathVariable("id") int id){
System.out.println(id);
return "a student~";
}
(二)使用post而不用post提交数据:
1.使用get,地址栏那里会显示你提交的参数
2.地址栏长度有限制,可能放不下那么多参数,会有错误
(三)接收表单form传过来的数据
后台方法的参数设置为form中定义的input中的name,即可自动获取对应的数据
@RequestMapping(path = "/student",method = RequestMethod.POST)
@ResponseBody
public String saveStudent(String name,int age){
System.out.println(name);
System.out.println(age);
return "保存成功!";
}
(四)返回一个html动态网页(使用Thymeleaf动态在html中添加对应数据)
两种方法:
1.返回ModelAndView(直观)
@RequestMapping(path = "/teacher",method = RequestMethod.GET)
public ModelAndView getTeacher(){
ModelAndView mav=new ModelAndView();
mav.addObject("name","张三");
mav.addObject("age",20);
mav.setViewName("/demo/view");
return mav;
}
2.model和view分开,把model放在方法的参数中(dispatcherServlet会自动创建model并传入方法,方法返回view。dispatcherServlet能获取到model和view。
@RequestMapping(path = "/school",method = RequestMethod.GET)
public String getSchool(Model model){
model.addAttribute("name","北京大学");
model.addAttribute("age","80");
return "/demo/view";
}