@RequestMapping修饰类
@RequestMapping("/springmvc")//此路径是相对于web应用根目录的路径 @Controller public class SpringMVCTest { private static final String SUCCESS = "success"; /** * @RequestMapping 除了修饰方法还可以修饰类 * 类定义处:提供初步的请求映射信息,相对于WEB应用的根目录 * 方法处:提供进一步的细分映射信息 * @return */ //此时请求应写为http://localhost:8080/SpringMVC/springmvc/testRequestMapping @RequestMapping("/testRequestMapping")//此路径是相对于类上面注解的路径 public String testRequestMapping() { System.out.println("testRequestMapping"); return SUCCESS;
为@RequestMapping指定请求方式
/** * 使用method来指定请求方式 * @return */ //此时通过http://localhost:8080/SpringMVC/springmvc/testMethod请求无效,必须为POST请求才响应 @RequestMapping(value="/testMethod", method=RequestMethod.POST) public String testMethod() { System.out.println("testMethod"); return SUCCESS; }
为@RequestMapping指定请求参数和请求头
//http://localhost:8080/SpringMVC/springmvc/testParamsAndHeaders?username=admin&age=10 这种方式HTTP Status 404 //http://localhost:8080/SpringMVC/springmvc/testParamsAndHeaders?username=admin&age=11 这种方式可以访问 @RequestMapping(value="testParamsAndHeaders", params={"username", "age!=10"}, headers={"Accept-Language=zh-CN,zh;q=0.8"}) public String testParamsAndHeaders() { return SUCCESS; }
@RequestMapping匹配Ant路径
//http://localhost:8080/SpringMVC/springmvc/testAntPath/aa/abc //@RequestMapping("/testAntPath/*/abc")//*表示任意字符 //http://localhost:8080/SpringMVC/springmvc/testAntPath/a/abc //@RequestMapping("/testAntPath/?/abc")//?表示任意一个字符 //http://localhost:8080/SpringMVC/springmvc/testAntPath/a/45/abc @RequestMapping("/testAntPath/**/abc")//**表示匹配多层路径 public String testAntPath() { System.out.println("testAntPath"); return SUCCESS; }
@RequestMapping的@PathVariable注解
/** * @PathVariable映射URL中的占位符到目标方法的参数中 * @param id * @return */ //http://localhost:8080/SpringMVC/springmvc/testPathVariable/45 @RequestMapping("/testPathVariable/{id}") public String testPathVariable(@PathVariable("id") Integer id){ System.out.println("testPathVariable:" + id); return SUCCESS; }
时间: 2024-10-27 06:12:34