zoukankan      html  css  js  c++  java
  • SpringBoot学习(七)-->SpringBoot在web开发中的配置

    SpringBoot在web开发中的配置

    Web开发的自动配置类:在Maven Dependencies-->spring-boot-1.5.2.RELEASE.jar-->org.springframework.boot.autoconfigure.web-->WebMvcAutoConfiguration.class中

    1、自动配置静态资源

    1) 、默认资源映射配置

    我们在启动应用的时候,可以在控制台中看到如下信息:

    2018-07-03 15:35:47.969 DEBUG 4880 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**/favicon.ico", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@46074492]
    2018-07-03 15:35:47.969 DEBUG 4880 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/webjars/**", locations=[class path resource [META-INF/resources/webjars/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@d78795]
    2018-07-03 15:35:47.969 DEBUG 4880 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@2c715e84]

    其中默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources)

    其中默认配置的 /webjars/** 映射到 classpath:/META-INF/resources/webjars/

    PS:上面的 static、public、resources 等目录都在 classpath: 下面(如 src/main/resources/static;src/main/resources/META-INF/resources)。

    如果我按如下结构存放相同名称的图片,那么Spring Boot 读取图片的优先级是怎样的呢?

    当我们访问:http://localhost:8088/test.bmp的时候,显示哪张图片?

    优先级顺序为:META/resources > resources > static > public 

    2)、自定义资源映射配置

     直接在 application.properties(或.yml)中配置:

    #静态资源处理
    #配置访问的端口号
    server.port=8088
    # 默认值为 /**
    spring.mvc.static-path-pattern=/**
    # 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
    #这里设置要指向的路径,多个使用英文逗号隔开,
    spring.resources.static-locations=/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

    3)、webjars

    什么是webjars?

    我们在Web开发中,前端页面中用了越来越多的js或CSS,如jQuery等等,平时我们是将这些Web资源拷贝到Java的目录下,这种通过人工方式拷贝可能会产生版本误差,拷贝版本错误,前端页面就无法正确展示。

    WebJars 就是为了解决这种问题衍生的,将这些Web前端资源打包成Java的Jar包,然后借助Maven这些依赖库的管理,保证这些Web资源版本唯一性。

    所以WebJars 就是将js, css 等资源文件放到 classpath:/META-INF/resources/webjars/ 中,然后打包成jar 发布到maven仓库中。

    示例:

    以jquery为例,文件存放结构为:

    META-INF/resources/webjars/jquery/2.1.4/jquery.js
    META-INF/resources/webjars/jquery/2.1.4/jquery.min.js
    META-INF/resources/webjars/jquery/2.1.4/jquery.min.map
    META-INF/resources/webjars/jquery/2.1.4/webjars-requirejs.js

    Spring Boot 默认将 /webjars/** 映射到 classpath:/META-INF/resources/webjars/ ,结合我们上面讲到的访问资源的规则,便可以得知我们在JSP页面中引入jquery.js的方法为:

    <script type="text/javascript" src="${pageContext.request.contextPath }/webjars/jquery/2.1.4/jquery.js"></script>

    想实现这样,我们只需要在pom.xml 文件中添加jquery的webjars 依赖即可,如下:

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>2.1.4</version>
    </dependency>

    4)、小结

      a、有这么多方式来管理我们的资源文件,但是我们在实际的开发中基本用不上,这些静态文件根本不会放在服务器处理,一个文件从几k到几十K甚至几百K一两M,服务器带宽低一点的访问一个页面几秒钟甚至十几秒几分钟之久。 

      b、所以,在我们实际的开发中,我们将静态文件交给nginx处理,我们可以有静态文件服务器,图片服务器,视频服务器(举个例子:阿里云的OSS对象存储)等等,来进行负载均衡,从而减轻服务器的压力。

      c、如果一定想用springboot的静态资源处理,那么我建议使用建webjars的方式,通过动态版本号(webjars-locator 的方式)来使用(因为第三方库在项目开发中变动频率很小,即便是变动也是版本号的修改)。 

    2、自动配置的视图解析器InternalResourceViewResolver

    视图配置的mvcProperties对象:

    在Maven Dependencies-->spring-boot-1.5.2.RELEASE.jar-->org.springframework.boot.autoconfigure.web的WebMvcProperties.class的View方法中:

     

    3、自定义消息转化器

    自定义消息转化器,只需要在@Configuration的类中添加消息转化器的@bean加入到Spring容器,就会被Spring Boot自动加入到容器中。

    默认会将详细转化为utf-8格式:(故此处采用ISO-8859-1来进行区分查看效果)

        @Bean
        public StringHttpMessageConverter stringHttpMessageConverter(){
            StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("ISO-8859-1"));
            return converter;
        }

    默认配置是这样的: 


     

    然后这样子写代码就不会出现乱码了:

        @RequestMapping("/hello")
        @ResponseBody //会使用详细转换器输出结果
        public String hello() {
            return "Hello Spring-Boot,淼淼之森";
        }

    4、自定义SpringMVC的配置

    有些时候我们需要自已配置SpringMVC而不是采用默认,比如说增加一个拦截器,这个时候就得通过继承WebMvcConfigurerAdapter然后重写父类中的方法进行扩展。

    import java.nio.charset.Charset;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.StringHttpMessageConverter;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration //申明这是一个配置
    public class MySrpingMVCConfig extends WebMvcConfigurerAdapter{
    
        // 自定义拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
                @Override
                public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                        throws Exception {
                    System.out.println("自定义拦截器............");
                    return true;
                }
                
                @Override
                public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                        ModelAndView modelAndView) throws Exception {
                    
                }
                
                @Override
                public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                        Exception ex) throws Exception {
                }
            };
            registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
        }
    
        // 自定义消息转化器的第二种方法,虽然创建了一个,但是仍然只有一个。因为默认没有才自动配置,有了就用用户自己定义的
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
            converters.add(converter);
        }
    
    }

    有关拦截器的内容请看下一篇文章。 

     

    参考文章:

    1、【Spring Boot 六】 静态资源处理:https://www.27wy.cn/archives/409

  • 相关阅读:
    安装yum源和gcc编译器遇到的问题
    (转)Linux下C++开发初探
    (转)求模和求余
    scanf———while(scanf ("%lu",&num) = =1)什么意思
    【Eclipse】 Alt+/ 代码提示问题解决方案
    【正则表达式】常用正则表达式
    【JAVA】Quartz中时间表达式的设置
    【Oracle】如何导库
    【JAVA】JMX简单使用方法
    【JAVA】Math.Round()函数常见问题“四舍5入”
  • 原文地址:https://www.cnblogs.com/mmzs/p/9259158.html
Copyright © 2011-2022 走看看