基于SpringMVC中的路径参数和URL参数实例
更新时间:2021-02-23 17:27:07 作者:佚名 我要评论(0)
2、路径参数实现方式(一个Controller方法)
@RequestMappin
1、SpringMVC中的路径参数就是指在路径中添加参数,用于实现伪静态是很好的。
2、路径参数实现方式(一个Controller方法)
@RequestMapping(value="/page/{name}/{age}",method=RequestMethod.GET) public String getName(ModelMap map,@PathVariable("name") String name,@PathVariable("age") int age) { map.addAttribute("name",name); map.addAttribute("age",age); return "name"; }
3、创建name.jsp文件
<%@page pageEncoding="UTF-8"%> <html> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <div> 名字:${name}<br/> 年龄:${age} </div> </body> </html>
4、在浏览器请求这个controller
http://localhost:8080/page/xiaoming/18
需要注意的是,我这里使用的编辑器是IDEA旗舰版
5、在controller中接受请求参数的实现(controller)
@RequestMapping(value="/result",method=RequestMethod.GET) public String resultParam(ModelMap map,@RequestParam String name,@RequestParam int age) { map.addAttribute("name",name); map.addAttribute("age",age); return "result"; }
6、创建result.jsp文件
<%@page pageEncoding="UTF-8"> <html> <head> <meta charset="UTF-8"> <title>测试</title> </head> <body> 名字:${name}<br/> 年龄:${age} </body> </html>
6、在浏览器中请求这个controller
http://localhost:8080/result?name=xiaoming&age=20
补充:spring mvc 之可选路径参数
在spring mvc中,注解@PathVariable可以获得路径参数,但如果我想让路径参数可选呢?
@GetMapping({"/get/{offset}/{count}","/get/{offset}","/get/{offset}","/get"}) public void getGoods(@PathVariable(required = false) Integer offset,@PathVariable(required = false) Integer count){ System.out.println("offset:"+offset+"\ncount:"+count+"\n"); }
此时在这个例子中,offset和count都是可选的了,但是count存在时offset必须存在。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
- Spring MVC的参数绑定和返回值问题
- 为spring get请求添加自定义的参数处理操作(如下划线转驼峰)
- 详解Spring Boot Web项目之参数绑定
相关文章
matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)
在matplotlib中常用的标题主要三种:窗口标题、图像标题和子图标题。 先通过三个案例简要说明这三类标题的实现。 窗口标题、图像标题,子图2021-02-23matplotlib之pyplot模块之标题(title()和suptitle())
matplotlib 源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)添加链接描述简单比较了matplotlib中的标题。 使用title()设置子图2021-02-23
最新评论