spring mvc:练习 @RequestParam和@PathVariable
@RequestParam: 注解将请求参数绑定到你的控制器方法参数
@PathVariable: 注释将一个方法参数绑定到一个URI模板变量的值
@RequestParam: 注解将请求参数绑定到你的控制器方法参数
@RequestMapping(value="/example/user")public String UserInfo(Model model, @RequestParam(value="name", defaultValue="Guest") String name)
实例:
package springmvc;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;@Controllerpublic class RequestParamExampleController { @RequestMapping(value="/example/user") public String UserInfo(Model model, @RequestParam(value="name", defaultValue="Guest") String name) { model.addAttribute("name", name); if("admin".equals(name)) { model.addAttribute("email", "admin@google.com"); }else { model.addAttribute("email", "not set"); } return "example_user"; }}
@PathVariable: 注释将一个方法参数绑定到一个URI模板变量的值
@RequestMapping(value="/example/info/{language}/{id}/{name}")public String userInfo2(Model model, @PathVariable(value="language") String language, @PathVariable(value="id") Long id, @PathVariable(value="name") String name)
实例:
package springmvc;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.PathVariable;@Controllerpublic class RequestParamExampleController { @RequestMapping(value="/example/person/{name}/{age}") public String userPerson(Model model, @PathVariable(value="name") String name, @PathVariable(value="age") Long age) { model.addAttribute("name", name); model.addAttribute("age", age); String desc = ""; if(age > 20) { desc = "oldman"; }else { desc = "yongman"; } model.addAttribute("desc", desc); return "example_person"; }}