Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the @ RequestMapping annotation of Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to use the @ RequestMapping annotation of Java". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use the @ RequestMapping annotation of Java" can help you solve the problem.

I. Preface

Problem description: in a certain scenario, our code is the same in Service, but we want different prefixes to be accessible when accessing the Controller layer. As follows: / say/hello. We want to be able to access the interface through / a/say/hello and / b/say/hello without any external services, and we don't want to write two methods in Controller.

@ RestController@RequestMapping ("say") public class SayController {@ Autowired private SayService sayService; @ RequestMapping ("hello") public String hello () {return sayService.hello ();} II. Code implementation

Let's briefly explain the train of thought here:

1. After the Spring service is started, RequestMappingHandlerMapping, the implementation class of HandlerMapping, gets the methods modified by @ RequestMapping and other requests for comments, encapsulates them into HandlerMethod and saves them in RequestMappingHandlerMapping#MappingRegistry (HandlerMapping has multiple implementation classes, each with different rules).

two。 When DispatcherServlet receives the request, it will obtain the appropriate HandlerMapping according to url to form HandlerExecutionChain (processor execution chain), and then process the request through HandlerAdapter. Here, through HandlerMapping, the matching HandlerMethod will be obtained according to the request URL to make the method call.

So we have two ideas here:

1. When Spring loads HandlerMethod, set the matching rules of the current HandlerMethod to / a/say/hello/, / a/say/hello/, / b/say/hello/, which can be matched when access is requested.

two。 When processing the request, the access paths of / a/say/hello/ and / b/say/hello/ are matched to the / say/hello method through the interceptor.

This article chooses the first way of thinking (but the first way to think about it) to do a simple demo example, which is implemented as follows:

/ / Custom Distribution Notes @ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface RequestRouter {String [] value () default ";} package com.kingfish.springjdbcdemo.config;import lombok.SneakyThrows;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;import org.springframework.web.servlet.mvc.method.RequestMappingInfo;import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping Import javax.servlet.http.HttpServletRequest;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.Arrays;import java.util.Set;import java.util.stream.Collectors / * @ Author: kingfish * @ Email: kingfishx@163.com * @ Data: 2021-4-21 16:47 * @ Desc: implementation of routing HandlerMapping * / @ Component ("handlerMapping") public class RouterRequestMappingHandlerMapping extends RequestMappingHandlerMapping {/ / this method @ SneakyThrows @ Override protected RequestMappingInfo getMappingForMethod is called when encapsulating the method into HandlerMethod (Method method Class handlerType) {/ / get RequestRouter comments RequestRouter requestRouter = method.getAnnotation (RequestRouter.class) If (requestRouter = = null) {requestRouter = handlerType.getAnnotation (RequestRouter.class); if (requestRouter = = null) {for (Class handlerTypeInterface: handlerType.getInterfaces ()) {if ((requestRouter = handlerTypeInterface.getAnnotation (RequestRouter.class))! = null) {break } / / call the parent class to generate RequestMappingInfo RequestMappingInfo mappingForMethod = super.getMappingForMethod (method, handlerType); if (requestRouter! = null) {/ / if requestRouter is not empty, path processing String [] requestRouterValue = requestRouter.value () PatternsRequestCondition condition = mappingForMethod.getPatternsCondition (); / / gets the path that the current method matches, and then carries out the add process. Set patterns = condition.getPatterns (); Set routerPatterns = patterns.stream () / / stitching request path. You can customize the processing policy here. FlatMap (pattern-> Arrays.stream (requestRouterValue) .map (val-> "/" + val + pattern)) .flatMap (Collectors.toSet ()); / / add the stitched path to RequestMappingInfo patterns.addAll (routerPatterns);} return mappingForMethod } @ Configurationpublic class SpringConfig {@ Bean public DispatcherServlet dispatcherServlet () {DispatcherServlet dispatcherServlet = new DispatcherServlet (); / / disable loading of all handlerMapper, but only load bean dispatcherServlet.setDetectAllHandlerMappings (false) with beanName of handlerMapper; return dispatcherServlet;}}

It is important to note here:

1.HandlerMapping has multiple implementations in Spring, while dispatcherServlet.setDetectAllHandlerMappings (false); the parameter setting Spring discards loading multiple HandlerMapping, but only loads the

2.HandlerMapping . RequestMappingInfo contains a lot of information about the current method, including what kind of request path can match the method, so we get the information of RequestRouter here and add it to the matching path.

Third, effect

Add @ RequestRouter (value = {"a", "b"}) to the method

RestController@RequestMapping ("say") public class SayController {@ Autowired private SayService sayService; @ RequestRouter (value = {"a", "b"}) @ RequestMapping ("hello") public String hello () {return sayService.hello ();}}

/ a/say/hello/, / b/say/hello/ and / say/hello/ can all be accessed

That's all for "how to use Java's @ RequestMapping annotations". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report