本篇文章为大家展示了如何在SpringMVC中配置路径参数和URL参数,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
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必须存在。
上述内容就是如何在SpringMVC中配置路径参数和URL参数,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。