在上一随笔记录的基础上,现记录编写处理带有参数的Controller。
@Controller //这个注解会告知<context:component:scan> 将HomeController自动检测为一个Bean
@RequestMapping("/home") //这是根Url
public class HomeController {
private UserService userService;
@Autowired
public HomeController(UserService userService){
this.userService = userService;
}
//指定请求的路径,处理get请求的路径为 xxx/home/home.html的请求
@RequestMapping(value="home.html",method=RequestMethod.GET)
public String showHomePage(@RequestParam("name")String username,Model model){
model.addAttribute("username",username);
model.addAttribute("count", userService.getUsersCount());
return "home";
}
}
@RequestMapping("/home") //这是根Url
public class HomeController {
private UserService userService;
@Autowired
public HomeController(UserService userService){
this.userService = userService;
}
//指定请求的路径,处理get请求的路径为 xxx/home/home.html的请求
@RequestMapping(value="home.html",method=RequestMethod.GET)
public String showHomePage(@RequestParam("name")String username,Model model){
model.addAttribute("username",username);
model.addAttribute("count", userService.getUsersCount());
return "home";
}
}
注意到,在showHomePage方法的输入参数中,有@RequestParam("name")String
username这个参数,表示接收请求路径的参数name,并赋值给username.
如果请求的路径的参数名,与方法的入参的变量名一致,就可以不需要@RequestParam这个注解。
以上showHomePage这个方法处理的请求路径为:项目根路径/home/home.html?name="who"