自定义RequestMapping实现路径大小写忽视和版本控制

自定义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())
				.consumes
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值