`

SpringMVC之@RequestMapping用法

阅读更多


一、基本介绍
@RequestMapping 注解可以用在类上,也可以用在方法上。



@RestController
@RequestMapping("/home")
public class IndexController {
  @RequestMapping("/")
  String get(){
    return "Hello from get";
  }
  @RequestMapping("/index")
  String index(){
    return "Hello from index";
  }
}


/*

/home       请求,会调用 get()   方法,
/home/index 请求,会调用 index() 方法。

*/






二、一个 @RequestMapping ,匹配多个路径
@RestController
@RequestMapping("/home")
public class IndexController {

@RequestMapping(value={"", "/page", "page*","view/*,**/msg"})
  String indexMultipleMapping(){
    return "Hello from index multiple mapping.";
  }
}


/*

下面的路径都将匹配到 indexMultipleMapping() 方法进行处理:

  - localhost:8080/home
  - localhost:8080/home/
  - localhost:8080/home/page
  - localhost:8080/home/pageabc
  - localhost:8080/home/view/
  - localhost:8080/home/view/view


*/




三、@RequestMapping 中使用 @RequestParam 绑定参数
@RestController	
@RequestMapping("/home")
public class IndexController {
  


/*

匹配:localhost:8090/home/id?_id=5


*/
  @RequestMapping(value = "/id")								
  String getIdByValue(@RequestParam("_id") String personId){
    System.out.println("ID is "+personId);
    return "Get ID from query string of URL with value element";
  }


/*

匹配:localhost:8090/home/personId?personId=5

注意:如果方法参数的 personId 名称 与 请求路径中参数的名称一致,
     则可以省略 @RequestParam 后面小括号的内容
*/

  @RequestMapping(value = "/personId")							
  String getId(@RequestParam String personId){
    System.out.println("ID is "+personId);	
    return "Get ID from query string of URL without value element";	
  }
}


/*

@RequestParam 的 required 属性用法示例

*/
@RestController
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(value = "/name")
  String getName(@RequestParam(value = "person", required = false) String personName){
    return "Required element of request param";
  }
}


/*

@RequestParam 的 defaultValue 属性用法示例

*/
@RestController	
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(value = "/name")
  String getName(@RequestParam(value = "person", defaultValue = "John") String personName ){
    return "Required element of request param";
  }
}




四、@RequestMapping 结合 HTTP 请求方法使用

HTTP 请求方法包括:  GET, PUT, POST, DELETE, and PATCH.

@RestController
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(method = RequestMethod.GET)
  String get(){
    return "Hello from get";									
  }
  @RequestMapping(method = RequestMethod.DELETE)
  String delete(){
    return "Hello from delete";
  }
  @RequestMapping(method = RequestMethod.POST)
  String post(){
    return "Hello from post";
  }
  @RequestMapping(method = RequestMethod.PUT)
  String put(){
    return "Hello from put";
  }
  @RequestMapping(method = RequestMethod.PATCH)
  String patch(){
    return "Hello from patch";
  }
}

/*
请求路径都是 /home,但是根据 http 发送的请求方法的不同,
匹配不同的处理方法。

*/




/*

@RequestMapping 根据请求方法,的简写

*/

@RequestMapping("/home")
public class IndexController {
  @GetMapping("/person")
  public @ResponseBody ResponseEntity<String> getPerson() {
    return new ResponseEntity<String>("Response from GET", HttpStatus.OK);
  }
  @GetMapping("/person/{id}")
  public @ResponseBody ResponseEntity<String> getPersonById(@PathVariable String id){
    return new ResponseEntity<String>("Response from GET with id " +id,HttpStatus.OK);				  }
  @PostMapping("/person")
  public @ResponseBody ResponseEntity<String> postPerson() {
    return new ResponseEntity<String>("Response from POST method", HttpStatus.OK);
  }
  @PutMapping("/person")
  public @ResponseBody ResponseEntity<String> putPerson() {
    return new ResponseEntity<String>("Response from PUT method", HttpStatus.OK);
  }
  @DeleteMapping("/person")
  public @ResponseBody ResponseEntity<String> deletePerson() {
    return new ResponseEntity<String>("Response from DELETE method", HttpStatus.OK); 
  }
  @PatchMapping("/person")
  public @ResponseBody ResponseEntity<String> patchPerson() {
    return new ResponseEntity<String>("Response from PATCH method", HttpStatus.OK);	
  }
}



五、@RequestMapping 缩小匹配范围:限制输入和输出格式


@RestController
@RequestMapping("/home")
public class IndexController {

/*

只匹配消费类型是 application/JSON 的请求
*/
  @RequestMapping(value = "/prod", produces = {"application/JSON"})
  @ResponseBody
  String getProduces(){
    return "Produces attribute";
  }


/*

只匹配输入类型是 application/JSON 或 application/XML 的请求
*/
  @RequestMapping(value = "/cons", consumes = {"application/JSON", "application/XML"})
  String getConsumes(){
    return "Consumes attribute";
  }
}







六、@RequestMapping 缩小匹配范围:限制 Headers 请求头

/*

只匹配 header 中含有:content-type=text/plain 的请求
*/
@RestController	
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(value = "/head", headers = {"content-type=text/plain"})
  String post(){	
    return "Mapping applied along with headers";	
  }								
}


/*

只匹配 header 中含有:content-type=text/plain 或 content-type=text/html 的请求
*/
@RestController
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(value = "/head", headers = {"content-type=text/plain", "content-type=text/html"})		  String post(){
    return "Mapping applied along with headers";
  }								
}






七、@RequestMapping 缩小匹配范围:限制请求参数

@RestController
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(value = "/fetch", params = {"personId=10"})
  String getParams(@RequestParam("personId") String id){
    return "Fetched parameter using params attribute = "+id;
  }
  @RequestMapping(value = "/fetch", params = {"personId=20"})
    String getParamsDifferent(@RequestParam("personId") String id){
    return "Fetched parameter using params attribute = "+id;
  }
}






八、@RequestMapping 动态匹配 URL
@RestController
@RequestMapping("/home")
public class IndexController {
  @RequestMapping(value = "/fetch/{id}", method = RequestMethod.GET)
  String getDynamicUriValue(@PathVariable String id){
    System.out.println("ID is "+id);
    return "Dynamic URI parameter fetched";						
  } 
  @RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = RequestMethod.GET)
    String getDynamicUriValueRegex(@PathVariable("name") String name){
    System.out.println("Name is "+name);
    return "Dynamic URI parameter fetched using regex";		
  } 
}




九、@RequestMapping 设定默认匹配的方法
@RestController
@RequestMapping("/home")
public class IndexController {

  /*
这个 @RequestMapping() 什么值也没设定,作为默认处理 /home 请求的方法。
*/
  @RequestMapping()
  String default(){									
    return "This is a default method for the class";
  }
}






转载请注明,
原文出处: http://lixh1986.iteye.com/blog/2429836













-

引用:
https://springframework.guru/spring-requestmapping-annotation/






  • 大小: 32.2 KB
分享到:
评论

相关推荐

    Springmvc中 RequestMapping 属性用法归纳.docx

    简介: @RequestMapping RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该...RequestMapping注解有六个属性(分成三类进行说明)与六个基本用法,

    springmvc-RequestMapping:根据映射的 URL 定位具有 @RequestMapping 注释的整个类或特定处理程序方法

    springmvc-RequestMapping 根据映射的 URL 定位具有 @RequestMapping 注释的整个类或特定处理程序方法目的 : 大多数时候,当我们不熟悉基于 spring 框架的 Web 应用程序时,我们只有一种选择来定位 Controller 类或...

    springmvc02.zip

    使用方法直接下载导入到自己的eclipse工具中,tomcat进行部署,访问地址:http://ip:port/springmvc02/toLogin.do;将login.jsp中的form表单中的action请求路径修改为LoginController类中的相应的@RequestMapping("/...

    手写SpringMVC注解动态调用控制器方法.zip

    刚接触SpringMVC几天、代码肯定比不上大佬ε≡٩(๑&gt;₃&lt;)۶ ,手下留情,谢谢 ...@Controller、@RequestMapping、@requestParam用法及原理 _φ(❐_❐✧ 人丑就要多读书 不熬夜不追剧~( ̄▽ ̄)~* 

    SpringMVC注解开发的详解.doc

    分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。

    基于SSM的高职院校教学中心可视化教学分析系统(源码+部署说明+演示视频).zip

    该系统的源码和部署说明可以帮助开发者更好地理解和使用该系统,同时演示视频也可以让用户更加直观地了解系统的使用方法和操作流程。如果您需要开发或管理类似的教学中心管理系统,这款基于SSM的高职院校教学中心...

    springMVC中 RequestMapping的使用.docx

    该注解的最大作用:完成"请求路径"到"处理该请求方法"之间的映射关系,放在类上方,主要是给类中的方法,定义一个namespace(命名空间)、放在方法上表示请求到达方法的具体位置。 比如:(那么访问路径就是“/sys/...

    0325_SpringMVC.html

    * 4)、来看请求地址和@RequestMapping标注的哪个匹配,来找到到底使用那个类的哪个方法来处理 * 5)、前端控制器找到了目标处理器类和目标方法,直接利用返回执行目标方法; * 6)、方法执行完成以后会有一个...

    license.txt

    我们在springmvc中使用json经常出现乱码格式 如下图: 我们可以在@RequestMapping()中配置,produces = "application/json;charset=utf-8",这样就解决了我们乱码, 但是,如果我们每次使用Json...

    SpringMVC学习笔记整合搭建框架

    2、@RequestMapping注解的使用 3、Controller方法返回值 4、SpringMVC中异常处理 5、图片上传处理 6、Json数据交互 7、SpringMVC实现RESTful 8、拦截器 2.Spring入门 2.1.Springmvc是什么 3.3.jdbc编程步骤: 1、...

    springmvc 发送ajax出现中文乱码的解决方法汇总

    使用spingmvc,在JS里面通过ajax发送请求,并返回json格式的数据,从数据库拿出来是正确的中文格式,展示在页面上就是错误的??,研究了一下,有几种解决办法。  我使用的是sping-web-3.2.2,jar  方法一:  在...

    SpringMVC实现文件上传.docx

    Spring MVC是一个在Java平台上构建Web应用程序的框架...您可以使用@RequestMapping注解指定处理文件上传的URL路径。 定义表单: 在HTML表单中,设置enctype属性为multipart/form-data,以便能够上传文件。创建一个表单

    SpringMvcGuide:一个用来记录SpringMVC细节的项目

    SpringMVC的相关用法主要内容@RequestMapping注解中相关参数的意义参考RequestMappingController类.Controller中方法的参数可以定义的类型统计普通常用的基本参数没有写, 介绍了一些稍微冷门但是还有点用的, 参考...

    基于Spring MVC的CRUD控制器

    基于SpringMVC,实体的Controller只要继承该类即刻拥有增删改查的的方法。 比如: @Controller @RequestMapping("/role") RoleController extends CrudController&lt;Role&gt; 只要简单的继承就可以通过/role/save.do...

    spring mvc 3.2 参考文档

    默认handler基于 @Controller 和 @RequestMapping 注解,提供范围广泛且灵活的处理方法。从Spring3.0开始支持REST,主要通过 @PathVariable 注解和其他特性来支持。 在Spring Web MVC 中,您可以使用任何对象作为...

    spring-base64-url-decoder:添加 MVC 参数注释和 HandlerMethodArgumentResolver 以启用解码 Base64 编码的 URL 参数

    二进制文件Maven 示例: &lt; dependency&gt; &lt; groupId&gt;de.is24.spring&lt;/ groupId&gt; &lt; artifactId&gt;base64-url-decoder&lt;/ artifactId&gt; &lt; version&gt;1.0&lt;/ version&gt; 用法根据此示例,在 MVC 控制器中使用@DecodedUri注释来注释...

    SSM笔记-SpringMVC REST风格、基本标签初识

    SSM笔记-SpringMVC REST风格初识、RequestMapping/PathVariable/RequestParam/RequestHeader/CookieValue基本使用方法

    dynafilter-proj:Spring MVC中Json序列化的动态对象过滤

    @DynaFilter注释用于从任何数据类型中过滤掉感兴趣的字段,并与通常的请求处理程序方法结合使用: @RequestMapping ( value = " collection " , method = GET , produces = " application/json " )@DynaFilter ( ...

    用ajax传递json到前台中文出现问号乱码问题的解决办法

    我使用的Springmvc,在controller层传输一个json到前台,后台显示没问题,中文正常显示而到了前台 中文就变成了问号。 后来发现,因为在controller中返回json用了@ResponseBody,而spring源码中@ResponseBody 的实现...

    SpringMVC示例

    本次实践内容包括RequestMapping关键字修饰类和方法(请求方式、请求参数&请求头、Ant风格路径)、PathVariable注解、HiddenHttpMethodFilter 过滤器(将Get请求转换成PUT、DELETE请求)、 RequestParam 注解、...

Global site tag (gtag.js) - Google Analytics