首页 > 编程技术 > java

SpringBoot配置项目访问路径URL的根路径方式

发布时间:2022-1-27 16:59 作者:春风化作秋雨

配置项目访问路径URL的根路径

1.SpringBoot在2.0之前版本

使用server.context-path

server.context-path=/api

2.SpringBoot在2.0之后版本

使用server.servlet.context-path

server.servlet.context-path=/api

设置默认访问路径

一共有两种方法。

1.继承WebMvcConfigurerAdapter类或实现WebMvcConfigurer接口

创建一个config包,然后在包内创建MyMvcConfig类。

import org.springframework.context.annotation.Configuration; 
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) { 
        registry.addViewController("/").setViewName("index"); 
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE); 
        super.addViewControllers(registry); 
    } 
}

注意:如果用这个方法html页面需要在static下,不然会出现404错误,找不到页面。

2.@Controller路由设置

在controller层中创建一个IndexController类

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; 
@Controller
public class IndexController {
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://adong.blog.csdn.net/article/details/113064582

标签:[!--infotagslink--]

您可能感兴趣的文章: