Spring MVC 访问Url和参数实现忽略大小写
admin 2019-06-12 23:08:53 218人已围观
最近有些网址在在提交搜索引擎收录的时候发现都变成了小写,而我的实际网址是区分大小写的,导致很多网址虽然被收录了但是还是访问不了我的网站,网址类似如下:
- 》 https://www.onekbit.com/shareFavoriteAction/index.do (可以访问)
- 》 https://www.onekbit.com/sharefavoriteaction/index.do (无法访问)
- 》 https://www.onekbit.com/IndustryCategory/index/456 (可以访问)
- 》 https://www.onekbit.com/industrycategory/index/456 (无法访问)
- 》 https://www.onekbit.com/adminUserAction/toIndex.do (可以访问)
- 》 https://www.onekbit.com/adminuseraction/toindex.do (无法访问)
为了不让搜索引擎浪费收录,我得想办法实现SpringMVC不区分大小写,经过我自己的修改基本实现了这个忽略访问url和参数大小写的问题,简单记录一下我的处理过程:
第一步、继承AntPathMatcher类
import java.util.Map;
import org.springframework.util.AntPathMatcher;
public class CaseInsensitivePathMatcher extends AntPathMatcher {
protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) {
return super.doMatch(pattern.toLowerCase(), path.toLowerCase(), fullMatch, uriTemplateVariables);
}
}
第二步、修改springmvc的配置文件
<bean id="caseInsensitivePathMatcher" class="com.onekbit.frame.mysystem.CaseInsensitivePathMatcher"/>
<mvc:annotation-driven>
<mvc:path-matching path-matcher="caseInsensitivePathMatcher"/>
</mvc:annotation-driven>
第三步、注意项目中@PathVariable参数
@SuppressWarnings("unchecked")
@RequestMapping(value="/index/{folderId}",method=RequestMethod.GET)
public ModelAndView index(@PathVariable("folderid") int folderId,HttpServletRequest request,HttpServletResponse response)
注意这里的@pathvariable使用了不同的大小写别名。
原理分析:
URL请求到达DispatcherServlet时,会使用RequestMappingHandlerMapping查找URL匹配的HandlerMethod。其中,会用到RequestMappingHandlerMapping的基类AbstractHandlerMappingPathMatcher的PathMatcher属性进行URL映射处理。RequestMappingHandlerMapping类默认使用AntPathMatcher作为PathMatcher,通过设置AntPathMatcher的CaseSensitive属性为false,来指定PathMatcher对URL的大小字母不敏感。
分享到:
编辑发布时间:2019-06-12 23:08:53