欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring Boot 定制URL匹配规则的方法

时间:2021-05-15 09:08:35|栏目:JAVA代码|点击:

事情的起源:有人问我,说编写了一个/hello访问路径,但是吧,不管是输入/hello还是/hello.html,还是/hello.xxx都能进行访问。当时我还以为他对代码进行处理了,后来发现不是,后来发现这是Spring Boot路由规则。好了,有废话了下,那么看看我们解决上面这个导致的问题。

构建web应用程序时,并不是所有的URL请求都遵循默认的规则。有时,我们希望RESTful URL匹配的时候包含定界符“.”,这种情况在Spring中可以称之为“定界符定义的格式”;有时,我们希望识别斜杠的存在。Spring提供了接口供开发人员按照需求定制。

核心的开发步骤就是两步:

(1)启动类 extends WebMvcConfigurationSupport

(2)重写configurePathMatch方法;

具体实现代码:

package com.kfit; 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 
/**
 *
 * @author Angel --守护天使
 * @version v.0.1
 * @date 2016年7月29日下午7:06:11
 */
@SpringBootApplication
public class ApiCoreApp extends WebMvcConfigurationSupport{
  
  
  /**
   * 1、 extends WebMvcConfigurationSupport
   * 2、重写下面方法;
   * setUseSuffixPatternMatch : 设置是否是后缀模式匹配,如“/user”是否匹配/user.*,默认真即匹配;
   * setUseTrailingSlashMatch : 设置是否自动后缀路径模式匹配,如“/user”是否匹配“/user/”,默认真即匹配;
   */
  @Override
  publicvoid configurePathMatch(PathMatchConfigurer configurer) {
    configurer.setUseSuffixPatternMatch(false)
          .setUseTrailingSlashMatch(true);
  }
  
  publicstaticvoid main(String[] args) {
    SpringApplication.run(ApiCoreApp.class, args);
  }
}
 

其中访问代码:

  @RequestMapping("/user")
  public String hello(){
    return"/user";
  }

以上代码有两句核心的代码:

setUseSuffixPatternMatch(boolean useSuffixPatternMatch):

设置是否是后缀模式匹配,如“/user”是否匹配/user.*,默认真即匹配;

当此参数设置为true的时候,那么/user.html,/user.aa,/user.*都能是正常访问的。

当此参数设置为false的时候,那么只能访问/user或者/user/( 这个前提是setUseTrailingSlashMatch 设置为true了)。

setUseTrailingSlashMatch (boolean useSuffixPatternMatch):

设置是否自动后缀路径模式匹配,如“/user”是否匹配“/user/”,默认真即匹配;

当此参数设置为true的会后,那么地址/user,/user/都能正常访问。

当此参数设置为false的时候,那么就只能访问/user了。

当以上两个参数都设置为true的时候,那么路径/user或者/user.aa,/user.*,/user/都是能正常访问的,但是类似/user.html/ 是无法访问的。

当都设置为false的时候,那么就只能访问/user路径了。

上一篇:详解Lombok快速上手(安装、使用与注解参数)

栏    目:JAVA代码

下一篇:Javaweb开发环境Myeclipse6.5 JDK1.6 Tomcat6.0 SVN1.8配置教程

本文标题:Spring Boot 定制URL匹配规则的方法

本文地址:http://www.codeinn.net/misctech/122220.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有