卜若的代码笔记系列-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;
    }
}


发布了202 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37080133/article/details/102554295