1.通过@RequestParam 坏处:参数变成url地址的一部分,如果没有值,则报错
如果是必不可少的参数,建议前面加@ RequestParam
解决办法是,设置required为false
@RequestParam(value="age",required=false,defaultValue="0")
参数:
value:表示传递的属性名
required:表示是否为必须的
defaultValue:表示设置默认值---当传递的参数无法自动转型时
@Controller public class welcome { @RequestMapping({"welcome"}) //@RequestParam("name") String name 意思是:拦截器拦截名为name的属性然后把值赋给String name public String welcomeTesr(@RequestParam("name") String name){ System.out.println("wenlcome"+name); return "/welcome"; } }
2.通过直接配置参数 坏处:没传参数时候,值为null
@Controller public class welcome { @RequestMapping({"welcome"}) public String welcomeTesr(String name){ System.out.println("wenlcome"+name); return "/welcome"; } }
3.如果是动态参数,使用@pathvariable 接收
@RequestMapping(value="/{username}",method=RequestMethod.GET) public String show (@PathVariable(value="username") String username,Model model){ System.out.println(username); /*model.addAttribute(users.get(username));*/ return "/users/show"; }
请求头包含了若干个属性,服务器可据此获取客户端的信息,通过@RequestHeader即可将求头中的属性值绑定到处理方法的参数中
@RequestMapping(value="/handler") public String handler(@RequestHeader("Accept-Encoding") String encoding){ System.out.println(endoding); }
@CookieValue可以让方法绑定某个cookie值
@RequestMapping("/testCookieValue") public String testCookieValue(@cookieValue("JSESSIONID") String sessionId){ System.out.println("testCookieValue:sessionId:"+sessionId); }
如:user.getName(),user.getId()
<form action="sh/testPOJO" method="POST"> username:<input type="text" name="username"> passwrod:<input type="password" name="password"> <input type="submit" value="提交" /> </form>
@Controller @RequestMapping(value = "/sh") public class SpringHandler { @RequestMapping(value="testPOJO",method=RequestMethod.POST) public String testPOJO(User user){ System.out.println(user); return null; } }
public class User { private String username; private String password; }
writer,调用的是response的返回getWriter()的方法
@RequestMapping(value="testServletApi") public String testServletApi(HttpServletRequest reqeust,HttpServletResponse response){ System.out.println(reqeust+":"+response); return HELLO; }