当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot 定制URL匹配规则的方法

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

红鼠网,鸡西车祸,面包大王全集下载

事情的起源:有人问我,说编写了一个/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路径了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网