Spring MVC 学习总结(二)——@RequestMapping详解

本文详细解析了Spring Framework中的@RequestMapping注解,介绍了其8个属性的作用,包括value、name、path、method、params、headers、consumes和produces。并通过示例展示了如何使用这些属性进行灵活的URL映射。

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

@RequestMapping详解

@RequestMapping注释用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。该注解共有8个属性,注解源码如下:

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.Callable;

import org.springframework.core.annotation.AliasFor;

/**
 * 用于映射url到控制器类或一个特定的处理程序方法.
 */
//该注解只能用于方法或类型上
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {

    /**
     * 指定映射的名称
     */
    String name() default "";

    /**
     * 指定请求的路径映射,指定的地址可以是uri模板,别名为path
     */
    @AliasFor("path")
    String[] value() default {};

    /** 别名为value,使用path更加形象
     * 只有用在一个Servlet环境:路径映射URI(例如“/myPath.do”)。
     * Ant风格的路径模式,同时也支持(例如,“/myPath/*.do”)。在方法层面,在主要的映射在类型级别表示相对路径(例如,“edit.do”)
     * 的支持。路径映射的URI可能包含占位符(例如“/$ {}连接”)
     */
    @AliasFor("value")
    String[] path() default {};

    /**
     * 指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE. 收窄请求范围 The
     * HTTP request methods to map to, narrowing the primary mapping: GET, POST,
     * HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
     */
    RequestMethod[] method() default {};

    /**
     * 映射请求的参数,收窄请求范围 The parameters of the mapped request, narrowing the
     * primary mapping.
     */
    String[]params() default {};

    /**
     * 映射请求头部,收窄请求范围 The headers of the mapped request, narrowing the primary
     * mapping. RequestMapping(value = "/something", headers =
     * "content-type=text/*")
     */
    String[] headers() default {};

    /**
     * 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html,收窄请求范围 The
     * consumable media types of the mapped request, narrowing the primary
     * mapping.
     */
    String[] consumes() default {};

    /**
     * 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回 The producible media types
     * of the mapped request, narrowing the primary mapping. produces =
     * "text/plain" produces = {"text/plain", "application/*"} produces =
     * "application/json; charset=UTF-8"
     */
    String[] produces() default {};
}

2.1、value 属性指定映射路径或URL模板

指定请求的实际地址,指定的地址可以是URL模板,正则表达式或路径占位,该属性与path互为别名关系,@RequestMapping("/foo")} 与 @RequestMapping(path="/foo")相同。该属性是使用最频繁,最重要的一个属性,如果只指定该属性时可以把value略去。Spring Framework 4.2引入了一流的支持声明和查找注释属性的别名。@AliasFor注解可用于声明一双别名属性,来给注解的属性起别名, 让使用注解时, 更加的容易理解(比如给value属性起别名, 更容易让人理解)。先看一个官网的示例:

package cn.liuw.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.liuw.domain.User;
import cn.liuw.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	//访问 http://localhost:8080/user
	@RequestMapping
	public String index(){
		return "user";
	}
	//指定具体路径字符
	@RequestMapping(path = "/list",method = RequestMethod.GET)
	public List<User> getAllUser(){
		return userService.getUserList();
	}
	//路径变量占位,URI模板模式
	@RequestMapping(value = "/{name}",method = RequestMethod.GET)
	public List<User> getUserByUsername(@PathVariable String name){
		return userService.getUserByUsername(name);
	}
	
	@RequestMapping(value = "/{name}/{p1}/{p2}")
	public List<User> getUserByUsername(@PathVariable String name,
			@PathVariable int p1,@PathVariable int p2,Model model){
		model.addAttribute("sum", p1 + p2);
		return userService.getUserByUsername(name);
	}
	//处理多个 URI
	@RequestMapping(path = {"/1","/male"})
	public List<User> getMaleUser(){
		return userService.getMaleUser();
	}

}

2.2、name属性指定名称

为当前映射指定一个名称,不常用,一般不会指定。

2.3、path属性指定路径

先看源码中的path与value,定义如下:

@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};

2.4、@RequestMapping 快捷方式

Spring 4.3 引入了方法级注解的变体,也被叫做 @RequestMapping 的组合注解。组合注解可以更好的表达被注解方法的语义。它们所扮演的角色就是针对 @RequestMapping 的封装,而且成了定义端点的标准方法。

例如,@GetMapping 是一个组合注解,它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。 
方法级别的注解变体有如下几个:

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

如下两个方法是等价的:

@RequestMapping(value = "/{name}",method = RequestMethod.GET)
public List<User> getUserByUsername(@PathVariable String name){
	return userService.getUserByUsername(name);
}

@GetMapping(value = "/{name}")
public List<User> getUserByUsername1(@PathVariable String name){
	return userService.getUserByUsername(name);
}

本文参考自:https://www.cnblogs.com/best/p/5659596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值