SpringMVC的常用注解
springmvc常用注解
1.@controller 注解是否是控制器类
2. @requestMapping 请求路径的注解
在类和方法上都可以用
可以设置请求路径 也可以设置请求方法
1 2 3 | @RequestMapping ( "/User" ) @RequestMapping (value = "/login5" ,method = RequestMethod.POST) |
3.@RequestParam 用在请求参数上
如果传递的参数名和接收的参数名不一致 需要@RequestParam 注解
3.1 如果传递的参数名和接收的参数名一致
1 | <a href= "User/login2?name=aa&pwd=123" >登录 2 </a><br/> |
1 2 3 4 5 6 7 8 9 | @RequestMapping ( "/login2" ) public String login2(String name,String pwd) { System.out.println(name); System.out.println(pwd); return "success" ; } |
3.1 如果传递的参数名和接收的参数名不一致
1 | <a href= "User/login4?uname=lisi&upwd=123" >登录 4 </a><br/> |
1 2 3 4 5 6 7 8 9 10 | @RequestMapping ( "/login4" ) public String login4( @RequestParam (value= "uname" ) String name, @RequestParam (value= "upwd" ) String pwd) { System.out.println(name); System.out.println(pwd); return "success" ; } |
4.@PathVariable
在路径使用rest风格的时候 需要用@PathVariable注解路径上的参数
1 | <a href= "User/login3/zhangsan/123" >登录 3 </a><br/> |
1 2 3 4 5 6 7 8 9 10 | //rest风格 @RequestMapping ( "/login3/{aa}/{pwd}" ) public String login3( @PathVariable (value= "aa" ) String name, @PathVariable (value= "pwd" ) String pwd) { System.out.println(name); System.out.println(pwd); return "success" ; } |
5.@RequestHeader
请求头
1 | <a href= "User/testHeader2" >testHeader2</a><br/> |
1 2 3 4 5 6 7 | @RequestMapping ( "/testHeader2" ) public String testHeader2( @RequestHeader ( "host" ) String header) { System.out.print(header); return "success" ; } |
6.@CookieValue
获取cookie中的值
1 2 3 | <a href= "User/setCookie" >存cookie</a><br/> <a href= "User/getCookie" >取cookie</a> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @RequestMapping ( "/setCookie" ) public String setCookie(HttpServletResponse response) { Cookie cookie= new Cookie( "uname" , "zhangsan" ); cookie.setMaxAge( 3600 ); cookie.setPath( "/" ); response.addCookie(cookie); return "success" ; } @RequestMapping ( "/getCookie" ) public String getCookie( @CookieValue ( "uname" ) String uname) { System.out.println(uname); return "success" ; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)