卜若的代码笔记系列-Web系列-SpringBoot-第二十六章:Controller+@EnableWebMvc访问静态Html

1.当你使用@EnableWebMvc会屏蔽掉@EnableAutoConfiguration注解,这也是为什么,你在.Properties里面配置的东西不起作用!

这是我们直接在网上百度到的一些解决方案,我们想要不通过插件(templates)文件夹的方式,直接通过路由,such as:

 

直接去访问。

依照网上的玩法,直接gg

不过好在,Springboot虽然爽在默认大于配置,但是,有时候还是挺蛋疼的。比如不配置一下,就不能直接通过Controller访问html。不过好在,它保留了@EnableWebMvc注释,这样我们就有很多操作空间了

当我们使用了@EnableWebMvc注解之后,对于Springboot的默认配置是有影响的。

比如:默认路径,所以,当我们使用这个注解之后,一定要小心,一定要将默认的配置路径给弄上去

这个是必须的。

接下来,我们想要去分配静态资源,并且是通过路由的方式,我们其实可以这样搞,直接通过Bean注入的方式:

爽得不要不要的。

前缀,必须带上static,毕竟你使用get访问的时候,你不带上static,你想干嘛嘛!

 

算了,逐渐程序化,语文水准大幅度退后,so,我直接上代码啦~

package com.main;

import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableWebMvc
public class SpxConfig extends WebMvcConfigurerAdapter{

        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


    @Bean
    public InternalResourceViewResolver setupViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/static/");
        resolver.setSuffix("");
        return resolver;
    }
}


 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值