说明:本文章的内容转载至:https://my.oschina.net/happyBKs/blog/412788 如有侵权的地方,请联系本人,本人将会立即删除!
我们如何相对URL中的某些段 取出作为值来处理?
比如localhost:8080/webapp/s1/happybks/baymax中的happybks取出,我们应该怎么做呢?
以前获取我们从url请求中取值,都是在对get请求参数的获取,向这种从整个url中获取当中的一部分,springmvc提供了下面的利用@PathVariable注解映射请求URL中的占位符到控制器方法参数。
控制器方法:
package com.happyBKs.springmvc.handlers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @RequestMapping("/c3") @Controller public class RMHandler { @RequestMapping(value="p1/{id}") public String handleP1(@PathVariable("id") int pid) { System.out.println(pid+"+100="+(pid+100)); return "successrm"; } }注意:
@PathVariable注解需要加入3个import。
这里的@RequestMapping可以写成@RequestMapping(“p1/{id}”)
然后参数部分@PathVariable(“id”)和@RequestMapping(“p1/{id}”)注解的名称必须相同,都是id。
4.注解对应的参数被指定了类型,所以凡是请求url对应的占位符不符合该类型值得请求将被视为无法映射,及相关物理视图不存在。
我们看例子吧。
请求页面index6.jsp如下:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <a href="c3/p1/10">c3/p1/10</a><br/> <a href="c3/p1/20">c3/p1/20</a><br/> <a href="c3/p1/30">c3/p1/30</a><br/> </body> </html>点击三个超链接,控制台给出输出:
10+100=110
20+100=120
30+100=130
我们也可以手动在浏览器中输入url’,如 http://localhost:8080/mymvc/c3/p1/40
结果输出
40+100=140
这里需要注意的来了,如果我输入http://localhost:8080/mymvc/c3/p1/eee
服务器接到请求之后springDispatcherServlet发现eee不符合public String handleP1(@PathVariable(“id”) int pid)中的url占位符对应的参数类型,则请求存在语法错误。