RequestMapping

本文深入解析了SpringMVC框架中的@RequestMapping注解,详细介绍了其各项参数的使用方法,包括指定访问方式、请求参数设置、映射URL占位符、获取Cookie值等,以及如何使用Servlet原生API和返回不同类型的响应。

@RequestMapping注解

参数

  • value    

  • method

指定访问方式,如果访问方式不匹配,则无法进行访问。

	@RequestMapping(value="/testMethod",method=RequestMethod.POST)
	public String testMethod() {
		System.out.println("tsetMethod");
		return SUCCESS;
	}
  • params

请求参数的设置。

  1. params:表示请求必须包含名为param1的请求参数
  2. !params:表示请求不能包含名为param1的请求参数
  3. param1!=value1:表示请求包含名为param1的请求参数,但其值不为value1
  4. {"param1=value1","param2"}:请求必须包含名为param1和param2的两个请求参数,并且param1的值为value1
	@RequestMapping(value="/testParams",params= {"username","age!=10"})
	public String  testParams() {
		System.out.println("testParams");
		return SUCCESS;
	}

这里要求请求必须有username和age两个参数,并且age不为10。

 

@PathVariable:映射URL占位符到方法中

	@RequestMapping("/testPathVariable/{id}")
	public String testPathVariable(@PathVariable("id") Integer id){
		System.out.println("testPathVariable " + id);
		return SUCCESS;
	}

会把URL请求中的/testPathVariable后面的值保存到id中,这样我们就可以在方法中使用这个值。

 

@RequestParam:映射请求参数

	@RequestMapping(value="/testRequestParam")
	public String tsetRequestParam(@RequestParam(value="username",required=false) String username,@RequestParam(value="age",required=false,defaultValue="0") int age) {
		System.out.println("testRequestParam:"+username+"&"+age);
		return SUCCESS;
	}

通过@RequestParam可以比较快捷地获取到通过get方式访问的请求参数。

例如通过http://localhost:8080/SpingMVCTest1/springmvc/testRequestParam?username=Tom&age=22这个网址访问,我们可以在方法体中轻松获取到username和age的值。

 

@CookieValue:获取Cookie值

	@RequestMapping("/testCookieValue")
	public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) {
		System.out.println("testCookieValue:"+sessionId);
		return SUCCESS;
	}

该注解使用率不高。

 

可以使用Servlet原生的API作为目标方法的参数

	@RequestMapping("/testServlet")
	public void testServlet(HttpServletRequest request,HttpServletResponse response,Writer out) throws IOException {
		System.out.println("testServlet:"+request+"&"+response);
		out.write("hello springmvc");
		//return SUCCESS;
		
	}

支持以下各类型:

  • HttpServletRequest
  • HttpServletResponse 
  • HttpSession
  • java.serurity.Principal
  • Locale
  • InputStream
  • OutputStream
  • Reader
  • Writer

 

@RequestMapping()除了可以返回字符串类型,也可以返回ModelAndView类型。其中可以包含视图和模型信息。

	@RequestMapping("/tsetModelAndView")
	public ModelAndView testModelAndView() {
		String viewName=SUCCESS;
		ModelAndView modelAndView = new ModelAndView(viewName);
		
		//添加模型数据到ModelAndView中
		modelAndView.addObject("time",new Date());
		
		return modelAndView;
	}

SpringMVC会把ModelAndView的model中数据放入到request域对象中。

我们可以在页面上借助requestScope来访问该值。

time: ${requestScope.time}

 

我们也可以通过Map类型的参数来设置request对象中的值。(实际上也可以是Model类型或ModelMap类型)

	@RequestMapping("/testMap")
	public String testMap(Map<String,Object> map) {
		map.put("names", Arrays.asList("Tom","Jerry","Mike"));
		return SUCCESS;
	}

 

### Spring `@RequestMapping` 注解的用法详解 `@RequestMapping` 是 Spring MVC 中定义请求映射规则的核心注解,用于将 HTTP 请求映射到控制器的处理方法。它支持多种参数和使用方式,能够灵活地定义请求路径、请求方法以及其他相关配置。 #### 1. 基本用法 `@RequestMapping` 可以用于类和方法上。当用于类时,它定义了该类中所有方法的公共请求路径前缀;当用于方法时,它定义了具体的请求路径[^4]。例如: ```java @RequestMapping(value = "/user") @Controller public class UserServlet { @RequestMapping(value = "/login") public String login() { System.out.println("login ok...."); return "login_ok"; } } ``` 在这个例子中,`/user` 是类级别的路径,而 `/login` 是方法级别的路径,因此完整的请求 URL 是 `/user/login`。 #### 2. 指定请求方法 `@RequestMapping` 支持通过 `method` 属性来指定请求的方法类型,例如 `RequestMethod.GET` 或 `RequestMethod.POST`。这可以确保特定的方法仅响应特定类型的 HTTP 请求[^4]。 ```java @RequestMapping(value = "/login", method = RequestMethod.POST) public String login() { System.out.println("login ok...."); return "login_ok"; } ``` #### 3. 组合注解 从 Spring 4.3 开始,引入了 `@RequestMapping` 的组合注解,这些组合注解是 `@RequestMapping` 的封装,可以更好地表达方法的语义。例如: - `@GetMapping` 相当于 `@RequestMapping(method = RequestMethod.GET)` - `@PostMapping` 相当于 `@RequestMapping(method = RequestMethod.POST)` - `@PutMapping` 相当于 `@RequestMapping(method = RequestMethod.PUT)` - `@DeleteMapping` 相当于 `@RequestMapping(method = RequestMethod.DELETE)` - `@PatchMapping` 相当于 `@RequestMapping(method = RequestMethod.PATCH)` 使用这些组合注解可以使代码更加简洁和直观: ```java @GetMapping("/login") public String login() { System.out.println("login ok...."); return "login_ok"; } ``` #### 4. 其他常用参数 除了 `value` 和 `method` 外,`@RequestMapping` 还支持其他参数,例如: - `params`:指定请求必须包含的参数。 - `headers`:指定请求必须包含的 HTTP 头信息。 - `consumes`:指定请求的媒体类型(如 `application/json`)。 - `produces`:指定响应的媒体类型(如 `application/json`)。 ```java @RequestMapping(value = "/login", method = RequestMethod.POST, params = "type=admin") public String login() { System.out.println("login ok...."); return "login_ok"; } ``` #### 5. 获取 `@RequestMapping` 注解的方法及参数类型 可以通过反射机制获取 `@RequestMapping` 注解所对应的方法及参数类型。这在某些需要动态处理请求的场景中非常有用。例如,可以通过遍历类中的方法,检查其是否包含 `@RequestMapping` 注解,并获取相关的参数信息[^3]。 ```java Method[] methods = UserServlet.class.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping annotation = method.getAnnotation(RequestMapping.class); System.out.println("Method name: " + method.getName()); System.out.println("Request mapping value: " + Arrays.toString(annotation.value())); } } ``` #### 6. 总结 `@RequestMapping` 是 Spring MVC 中非常重要的注解,它不仅支持基本的 URL 映射,还允许通过多种参数进行更精细的控制。结合组合注解,可以进一步简化代码并提高可读性。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值