自定义RequestMapping
1. 实现忽视请求路径大小写的功能
-
需求分析
要实现请求路径大小写忽视的功能,就是把请求路径和RequestMapping中的路径都一起转为大写或者一起转为小写即可实现该功能
-
源码分析
我们知道所有的请求都是通过DispatcherServlet的doDispatch方法来处理的,所以我们先看这个方法
很明显,这个getHandler是通过请求路径来获取对应的Handler来处理的,我们继续跟进
继续跟进发现getHandler是一个接口,OK,我们打个断点,然后请求一下看下具体的实现类是谁
断点发现,mapping是RequestMappingHandlerMapping这个类,我们点开这个类查看
idea中ctrl+F12查看所有方法,直接就看到2个create方法
OK,我们先查看第一个create方法
这边最后调用了第二个create方法,我们继续查看
看到了创建出来的对象,paths在这边定义,也就是说,我们只需要把这边的paths里的值改了就可以了~那么开始我们的代码
先写配置类
package com.su.demo.config.requestmapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/**
* @author suchaobin
* @description: 自定义的HandlerMapping
* @date 2021/7/31 15:17
*/
@Slf4j
public class MyHandlerMapping extends RequestMappingHandlerMapping {
private final RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();
@Override
protected RequestMappingInfo createRequestMappingInfo(RequestMapping requestMapping, RequestCondition<?> customCondition) {
// 设置路径全部转化为小写
String[] paths = resolveEmbeddedValuesInPatterns(requestMapping.path());
for (int i = 0; i < paths.length; i++) {
paths[i] = paths[i].toLowerCase();
log.info("path={}", paths[i]);
}
RequestMappingInfo.Builder builder = RequestMappingInfo
.paths(paths)
.methods(requestMapping.method())
.params(requestMapping.params())
.headers(requestMapping.headers())
.