SpringMVC 学习笔记(二) @RequestMapping、@PathVariable等注解

本文详细介绍了SpringMVC框架中的请求映射机制,包括使用@RequestMapping注解配置URL映射,限定请求方法、参数及请求头,以及如何通过@PathVariable、@RequestParam等注解进行参数绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1. @RequestMapping映射请求

SpringMVC 使用 @RequestMapping 注解为控制器指定可以处理那些URL 请求


@requestMapping  可以定义在  和 方法 上 


  1. package com.ibigsea.springmvc.helloworld;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestMapping;  
  5.   
  6. @Controller  
  7. public class HelloWorld {  
  8.       
  9.     /** 
  10.      * 配置@RequestMapping 拦截 localhost:8080/springmvc/hello 请求  
  11.      * @return 
  12.      */  
  13.     @RequestMapping("/hello")  
  14.     public String helloWorld() {  
  15.         System.out.println("hello world");  
  16.         return "helloworld";  
  17.     }  
  18. }  
package com.ibigsea.springmvc.helloworld;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorld {
	
	/**
	 * 配置@RequestMapping 拦截 localhost:8080/springmvc/hello 请求 
	 * @return
	 */
	@RequestMapping("/hello")
	public String helloWorld() {
		System.out.println("hello world");
		return "helloworld";
	}
}


  1. package com.ibigsea.springmvc.helloworld;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestMapping;  
  5.   
  6. @Controller  
  7. @RequestMapping("/hello")  
  8. public class HelloWorld {  
  9.       
  10.     /** 
  11.      * 配置@RequestMapping 拦截 localhost:8080/springmvc/hello/world 请求  
  12.      * @return 
  13.      */  
  14.     @RequestMapping("/world")  
  15.     public String helloWorld(){  
  16.         System.out.println("hello world");  
  17.         return "helloworld";  
  18.     }  
  19. }  
package com.ibigsea.springmvc.helloworld;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/hello")
public class HelloWorld {
	
	/**
	 * 配置@RequestMapping 拦截 localhost:8080/springmvc/hello/world 请求 
	 * @return
	 */
	@RequestMapping("/world")
	public String helloWorld(){
		System.out.println("hello world");
		return "helloworld";
	}
}

@RequestMapping

– 类定义处:提供初步的请求映射信息。相对于 WEB 应用的根目录

– 方法处:提供进一步的细分映射信息。相对于类定义处的 URL。若

类定义处未标注 @RequestMapping,则方法处标记的 URL 相对于

WEB 应用的根目录

DispatcherServlet 截获请求后,就通过控制器上

@RequestMapping 提供的映射信息确定请求所对应的处理方法。

 

 

@RequestMapping 除了可以使用请求 URL 映射请求外,

还可以使用请求方法、请求参数及请求头映射请求


1.2. @RequestMapping限定请求方法、请求参数、请求头


  1. /** 
  2.      * 接收GET请求 
  3.      * @return 
  4.      */  
  5.     @RequestMapping(value="/get",method = RequestMethod.GET)  
  6.     public String get(){  
  7.         System.out.println("get");  
  8.         return "get";  
  9.     }  
  10.   
  11.     /** 
  12.      * 接收POST请求 
  13.      * @return 
  14.      */  
  15.     @RequestMapping(value="/post",method = RequestMethod.POST)  
  16.     public String post(){  
  17.         System.out.println("post");  
  18.         return "post";  
  19.     }  
  20.       
  21.     /** 
  22.      * 只接收 name 参数 
  23.      * @return 
  24.      */  
  25.     @RequestMapping(value="/params",params="name")  
  26.     public String params(String name){  
  27.         System.out.println("hello "+name);  
  28.         return "helloworld";  
  29.     }  
  30.       
  31.     /** 
  32.      * 只接收请求头中 Content-Type 为 text/html;charset=UTF-8的请求 
  33.      * @return 
  34.      */  
  35.     @RequestMapping(value="/headers",headers="Content-Type:text/html;charset=UTF-8")  
  36.     public String headers(){  
  37.         System.out.println("headers");  
  38.         return "helloworld";  
  39.     }  
/**
	 * 接收GET请求
	 * @return
	 */
	@RequestMapping(value="/get",method = RequestMethod.GET)
	public String get(){
		System.out.println("get");
		return "get";
	}

	/**
	 * 接收POST请求
	 * @return
	 */
	@RequestMapping(value="/post",method = RequestMethod.POST)
	public String post(){
		System.out.println("post");
		return "post";
	}
	
	/**
	 * 只接收 name 参数
	 * @return
	 */
	@RequestMapping(value="/params",params="name")
	public String params(String name){
		System.out.println("hello "+name);
		return "helloworld";
	}
	
	/**
	 * 只接收请求头中 Content-Type 为 text/html;charset=UTF-8的请求
	 * @return
	 */
	@RequestMapping(value="/headers",headers="Content-Type:text/html;charset=UTF-8")
	public String headers(){
		System.out.println("headers");
		return "helloworld";
	}

1.3. @RequestMapping匹配符

– ?:匹配文件名中的一个字符

– *:匹配文件名中的任意字符

– **** 匹配多层路径

实例:

URL : /user/*/create

-- /user/bigsea/create 、 /user/sea/create URL

URL : /user/**/create

-- /user/big/sea/create 、 /user/sea/big/create URL

URL : /user/create??

-- /user/createaa 、/user/createbb


1.4. @PathVariable 注解

带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。

  1. /** 
  2.      * localhost:8080/springmvc/hello/pathVariable/bigsea 
  3.      * localhost:8080/springmvc/hello/pathVariable/sea 
  4.      * 这些URL 都会 执行此方法 并且将  <b>bigsea</b>、<b>sea</b> 作为参数 传递到name字段 
  5.      * @param name 
  6.      * @return 
  7.      */  
  8.     @RequestMapping("/pathVariable/{name}")  
  9.     public String pathVariable(@PathVariable("name")String name){  
  10.         System.out.println("hello "+name);  
  11.         return "helloworld";  
  12.     }  
/**
	 * localhost:8080/springmvc/hello/pathVariable/bigsea
	 * localhost:8080/springmvc/hello/pathVariable/sea
	 * 这些URL 都会 执行此方法 并且将  <b>bigsea</b>、<b>sea</b> 作为参数 传递到name字段
	 * @param name
	 * @return
	 */
	@RequestMapping("/pathVariable/{name}")
	public String pathVariable(@PathVariable("name")String name){
		System.out.println("hello "+name);
		return "helloworld";
	}

JSP(这里指定全路径):


  1. <h1>pathVariable</h1>  
  2. <a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>  
  3. <br/>  
  4. <a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>  
  5. <br/>  
<h1>pathVariable</h1>
<a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>
<br/>
<a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>
<br/>

运行结果:


  1. hello bigsea  
  2. hello sea  
hello bigsea
hello sea


1.5. @RequestParam 绑定请求参数

在处理方法入参处使用 @RequestParam 可以把请求参数传递给请求方法

– value:参数名

– required:是否必须。默认为 true, 表示请求参数中必须包含对应的参数,若不存在,将抛出异常


  1. /** 
  2.      * 如果 required = true 则表示请求参数对应的 字段 必须存在.如果不存在则会抛出异常<br/> 
  3.      * @param firstName 可以为null 
  4.      * @param lastName 不能为null .为null报异常 
  5.      * @param age age字段表示如果没有 age 参数 则默认值为 0  
  6.      * @return 
  7.      */  
  8.     @RequestMapping("/requestParam")  
  9.     public String requestParam(@RequestParam(value="firstName",required=false)String firstName,  
  10.             @RequestParam( value="lastName" ,required = true) String lastName,  
  11.             @RequestParam(value="age",required = false ,defaultValue="0")int age) {  
  12.         System.out.println("hello my name is " + (firstName == null ? "" : firstName)  
  13.                                         + lastName + "," + age +" years old this year");  
  14.         return "helloworld";  
  15.     }  
/**
	 * 如果 required = true 则表示请求参数对应的 字段 必须存在.如果不存在则会抛出异常<br/>
	 * @param firstName 可以为null
	 * @param lastName 不能为null .为null报异常
	 * @param age age字段表示如果没有 age 参数 则默认值为 0 
	 * @return
	 */
	@RequestMapping("/requestParam")
	public String requestParam(@RequestParam(value="firstName",required=false)String firstName,
			@RequestParam( value="lastName" ,required = true) String lastName,
			@RequestParam(value="age",required = false ,defaultValue="0")int age) {
		System.out.println("hello my name is " + (firstName == null ? "" : firstName)
										+ lastName + "," + age +" years old this year");
		return "helloworld";
	}

Jsp:

  1. <a href="requestParam?firstName=big&lastName=sea" > name is bigsea , age is 0 </a>  
  2. <br/>  
  3. <a href="requestParam?lastName=sea&age=23" > name is sea , age is 23 </a>  
  4. <br/>  
  5. <a href="requestParam" > throws exception </a>  
<a href="requestParam?firstName=big&lastName=sea" > name is bigsea , age is 0 </a>
<br/>
<a href="requestParam?lastName=sea&age=23" > name is sea , age is 23 </a>
<br/>
<a href="requestParam" > throws exception </a>

运行结果:


  1. hello my name is bigsea,0 years old this year  
  2. hello my name is sea,23 years old this year  
hello my name is bigsea,0 years old this year
hello my name is sea,23 years old this year


1.6. @RequestHeader 获取请求头

请求头包含了若干个属性,服务器可据此获知客户端的信息,通过 @RequestHeader 即可将求头中的属性值绑定到处理方法的入参中

  1. /** 
  2.  * 获取请求头中的信息 
  3.  * @RequestHeader 也有 value ,required ,defaultValue 三个参数 
  4.  * @param userAgent 
  5.  * @param cookie 
  6.  * @return 
  7.  */  
  8. @RequestMapping("/requestHeader")  
  9. public String requestHeader(@RequestHeader("User-Agent")String userAgent,@RequestHeader("Cookie")String cookie){  
  10.     System.out.println("userAgent:["+userAgent+"]");  
  11.     System.out.println("cookie:["+cookie+"]");  
  12.     return "helloworld";  
  13. }  
	/**
	 * 获取请求头中的信息
	 * @RequestHeader 也有 value ,required ,defaultValue 三个参数
	 * @param userAgent
	 * @param cookie
	 * @return
	 */
	@RequestMapping("/requestHeader")
	public String requestHeader(@RequestHeader("User-Agent")String userAgent,@RequestHeader("Cookie")String cookie){
		System.out.println("userAgent:["+userAgent+"]");
		System.out.println("cookie:["+cookie+"]");
		return "helloworld";
	}
JSP:


  1. <a href="requestHeader" > requestHeader </a>  
<a href="requestHeader" > requestHeader </a>
运行结果:


  1. userAgent:[Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2383.0 Safari/537.36]  
  2. cookie:[JSESSIONID=DA3B15F559349EA2C3F08BE772FCAFD8]  
userAgent:[Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2383.0 Safari/537.36]
cookie:[JSESSIONID=DA3B15F559349EA2C3F08BE772FCAFD8]

1.7. @CookieValue 获取 cookie


  1. /** 
  2.      * 使用@CookieValue 绑定cookie值<br/> 
  3.      * 注解@CookieValue 也有 value ,required ,defaultValue 三个参数 
  4.      * @param session 
  5.      * @return 
  6.      */  
  7.     public String cookieValue(@CookieValue(value = "JSESSIONID", required= false)String session){  
  8.         System.out.println("JESSIONID:["+session+"]");  
  9.         return "helloworld";  
  10.     }  
/**
	 * 使用@CookieValue 绑定cookie值<br/>
	 * 注解@CookieValue 也有 value ,required ,defaultValue 三个参数
	 * @param session
	 * @return
	 */
	public String cookieValue(@CookieValue(value = "JSESSIONID", required= false)String session){
		System.out.println("JESSIONID:["+session+"]");
		return "helloworld";
	}

JSP:

  1. <a href="cookieValue" > cookieValue </a>  
<a href="cookieValue" > cookieValue </a>


运行结果


  1. JESSIONID:[A4196EEDFD829B40CC1975F029A61328]  
JESSIONID:[A4196EEDFD829B40CC1975F029A61328]

1.8. 源码分析









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值