微服务 SpringBoot 2.0(八):静态资源和拦截器处理

一文搞清楚静态资源和拦截器 —— Java面试必修

引言

接触一个web项目,首先要确认的就是入口,所以静态资源和拦截器在项目中是架构级的,在第五章我们整合了Thymeleaf模块,初次认识了SpringBoot对静态资源的默认支持。今天我们来继续学习SpringBoot中如何合理的存放静态资源,如何根据我们自身需要来进行扩展资源和拦截器的扩展。

在接下来的文章中,我在末尾处会公布源码,源码将托管在码云上

静态资源

工具

SpringBoot版本:2.0.4
开发工具:IDEA 2018
Maven:3.3 9
JDK:1.8

在web开发中,静态资源的访问是必不可少的,如:图片、js、css 等资源的访问。

Spring Boot 对静态资源访问提供了很好的支持,基本使用默认配置就能满足开发需求,Spring Boot 对静态资源映射提供了默认配置:

  1. 自动映射 localhost:8080/** 为
    • classpath:/META-INF/resources
    • classpath:/resources
    • classpath:/static
    • classpath:/public
  2. 自动映射 localhost:8080/webjars/** 为
    • classpath:/META-INF/resources/webjars/
    • 依据1类推

小实验:分别在4个文件夹下放置同名不同内容的图片,然后根据访问情况记录图片内容,访问 http://localhost:8080/a.png,然后一张张图片进行删减

你会发现这些路径的优先级顺序为:META-INF/resources > resources > static > public,即默认先找第一个文件夹,如果找到了,那么就直接取那张,否则接着找第二个文件夹,依此类推

实验图

此时,我们不需要多作些什么,只需要将静态资源放入 src/main/resources 目录下的 resources、static 或 public 文件夹下,可直接通过localhost:8080/a.jpg 定位相关资源,不要问为什么,因为这4个目录都是SpringBoot作为(默认)的静态资源路径

自定义静态资源映射

在实际开发中,可能需要自定义静态资源访问路径,那么可以继承**[WebMvcConfigurerAdapter | WebMvcConfigurer ]** 或 更改配置文件来实现

一、代码配置

在旧版中,一般继承 WebMvcConfigurerAdapter类,但由于2.0后,前者已经过时,WebMvcConfigurer 接口中定义了很多default方法(基于jdk1.8+ ),所以2.0后实现WebMvcConfigurer接口就好了。注:使用代码实现不会覆盖系统默认4种方式(同名定义除外)

SpringBoot 1.x写法


@Configuration
public class CustomerMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources2/")
                .addResourceLocations("classpath:/static2/")
                .addResourceLocations("classpath:/public2/")
                .addResourceLocations("classpath:/META-INF/resources2/");
    }
}

SpringBoot 2.0之后写法

@Configuration
public class CustomerMvcConfigurerAdapter implements WebMvcConfigurer {

    /**
     * 添加静态资源文件,外部可以直接访问地址
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //如下配置则能可以访问src/main/resources/mysource下面的文件
        registry.addResourceHandler("/myprofix/**").addResourceLocations("classpath:/mysource/");
        //如访问mysource文件夹下的a.jpg,则输入:localhost:8080/myprofix/a.jpg
    }
}

不管哪个版本,addResourceHandler方法是设置访问路径前缀,addResourceLocations方法设置资源路径,如果你想指定外部的目录也很简单,直接addResourceLocations指定即可,代码如下:

registry.addResourceHandler("/myprofix/**").addResourceLocations("file:E:/my/");
二、yml配置

配置文件跟代码一样,分两个:

  1. spring.mvc.static-path-pattern(访问路径),对应addResourceHandler方法
    此设置只是改变访问路径,4个文件夹的访问优先级不改变,下面举个例子
有4个文件夹分别为META-INF/resources、resources、static、public,它们各自文件夹下都放有a.jpg照片,
默认访问localhost:8080/a.jpg(优先级查看开头的小实验)。
但配置了下面第二行后访问路径则发生了改变,变为:localhost:8080/mysource/a.jpg,但优先级任然不变

# 默认值为 /**  如我要访问
spring.mvc.static-path-pattern: 

#下面配置生效后,其他4种方式无法访问,而且之前访问路径由:localhost:8080/a.jpg变成了localhost:8080/mysource/.jpg
spring.mvc.static-path-pattern: /mysource/**

结论:spring.mvc.static-path-pattern只是更改文件的访问路径,而原有的优先级不会发生改变


  1. spring.resources.static-locations(映射路径),对应addResourceLocations方法
    该配置将导致默认值失效,所以一般新增配置一定会兼容默认值
#资源文件映射路径,默认值:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations: 

#此行配置后其他文件夹将失效
spring.resources.static-locations: classpath:/public/

#如果我们需要新增一个文件夹newsource作为资源文件夹,我们通常加在默认配置的末尾
spring.resources.static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/newsource/

结论

代码实现也好,配置实现也罢,我们都应该分开去弄清楚,去学习访问路径映射路径,弄清楚他们各自的作用后,才能更好的搭配使用,接下来我们学习拦截器这一章

页面跳转小彩蛋

以前要访问一个页面需要先创建个Controller控制类,再写方法跳转到页面, 在这里配置后就不需要那么麻烦了,直接访问http://localhost:8080/toLogin就跳转到login.html页面了

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");
    }

注意,需要引入thymeleaf依赖,然后在templates下加入login.html页面,否则会跳转到Controller映射中去

拦截器

Spring Boot 1.x

在spring boot1.x中,使用拦截器,一般进行如下配置:

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
	@Resource
	private CsInterceptor csInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//自定义拦截器,添加拦截路径和排除拦截路径 
		registry.addInterceptor(csInterceptor).addPathPatterns("api/**").excludePathPatterns("api/login");
	}
}

但是在spring boot2.x中,WebMvcConfigurerAdapter被deprecated,虽然继承WebMvcConfigurerAdapter这个类虽然有此便利,但在Spring5.0里面已经deprecated了。

官方文档也说了,WebMvcConfigurer接口现在已经有了默认的空白方法,所以在Springboot2.0(Spring5.0)下更好的做法还是implements WebMvcConfigurer。

Spring Boot 2.x
自定义拦截器代码

定义一个登录拦截器,拦截需要登录的操作,若未登录则重定向至登录界面

@Component
public class CustomerInterceptor implements HandlerInterceptor {

    /**
     * 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag =true;
        UserSession user=(UserSession)request.getSession().getAttribute("userSession");
        if(null == user){
            //若为空则跳转到登录页
            response.sendRedirect("toLogin");
            flag = false;
        }else{
            flag = true;
        }
        return flag;
    }
 
    @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 {
    }
}
拦截器统一管理

addPathPatterns("/**")对所有请求都拦截,但是排除了/loginIn和/login请求的拦截

@Configuration
public class WebConfig implements WebMvcConfigurer {
    //自定义的拦截器
	@Resource
	private CustomerInterceptor customerInterceptor;

	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 自定义拦截器,添加拦截路径和排除拦截路径
        registry.addInterceptor(customerInterceptor).addPathPatterns("/**").excludePathPatterns("/login","/loginIn");
    }
}
新建Controller和提交表单界面
@Controller
public class UserController {


    @GetMapping("/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response){
        //跳转至登录界面
        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;
    }

    @PostMapping("/loginIn")
    @ResponseBody
    public Map<String,Object> loginIn(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new HashMap<String,Object>();
        String userName = request.getParameter("userName");
        System.out.print(userName);
        if("itmsbx".equals(userName)){
            request.getSession().setAttribute("userSession", new UserSession());
            map.put("result" , "1");
        }else{
            map.put("result" , "-1");
        }
        return map;
    }

    @RequestMapping("/manager")
    public ModelAndView manager(HttpServletRequest request, HttpServletResponse response){
        //跳转至管理后台
        ModelAndView modelAndView = new ModelAndView("manager");
        return modelAndView;
    }

登录界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Java面试必修</title>
</head>
<body>
除了登陆什么都没有
    <input type="text" name="userName" id="userName" value="itmsbx">
    <input type="button" onclick="loginIn()">
</body>
<script src="https://www.51object.com/static/heninet/js/jquery-1.11.3.min.js"></script>

<script>
    function loginIn(){
        var userName = $("#userName").val();
        $.ajax({
            type : "POST",
            url : "loginIn?userName=" + userName,
            dataType : "json",
            success : function(data) {
                if (data.result == "1") {
                    window.location.href ="/manager";
                } else {
                    alert("登录失败!");
                }
            }
        });

    }

</script>
</html>
访问

直接访问:http://localhost:8080/manager 将会被拦截器拦截并重定向至login界面
登录后便可直接进入manager界面

总结

通过这一章你是否弄懂了静态资源和拦截器的配置和使用,静态资源可以自定义进行配置。拦截器和普通的springmvc没有多大区别,同样是设置需要拦截的和不需要拦截的路径,下一章我们讲解SpringBoot2.0集成mybatis。

源码地址:

https://gitee.com/rjj1/SpringBootNote/tree/master/demo-res-interceptor


作者有话说:喜欢的话就请移步Java面试必修网,请自备水,更多干、干、干货等着你

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SpringBoot应用中,设置静态文件路径是非常常见的操作。如果你要在你的应用中使用静态资源,比如图片、css、js等,那么你就需要在静态资源文件夹中存放这些资源,在运行时加载这些资源以便于浏览器进行渲染。在SpringBoot2.0中,设置静态文件路径有多种方式,下面将详细介绍几种常用的方式。 1.在application.properties中配置 你可以直接在application.properties中配置静态文件路径,例如: spring.resources.static-locations= classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/ 说明: 1)spring.resources.static-locations这个属性就是让你指定静态文件的根路径。 2)这里指定了四个classpath下的路径,顺序不能颠倒,其中"classpath:/META-INF/resources/"是Spring Boot2.0及以上版本新增的,用来存放一些公共的静态资源文件。 2.在WebMvcConfigurer中配置 你可以自定义一个WebMvcConfigurer的配置类,实现addResourceHandlers方法,例如: @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); } } 说明: 1)这里指定了资源处理器registry,并添加了一个资源路径"/static/**"。 2)该资源路径对应的是classpath:/static/路径,即静态资源文件夹。 3.在@Configuration类中配置 如果你想更加灵活的配置静态资源路径,可以通过@Configuration注解进行配置,例如: @Configuration public class WebStaticConfigurer { @Value("${sba.static.path:''}") private String staticPath; @Bean public WebMvcConfigurer webMvcConfigurer() { return new WebMvcConfigurer() { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 配置静态资源路径 registry.addResourceHandler("/static/**") .addResourceLocations(staticPath); } }; } } 说明: 1)这里通过@Configuration注解定义了一个WebStaticConfigurer配置类,并进行了设置静态文件路径的操作,使得静态文件路径可以自行从配置文件中调取。 2)addResourceLocations(staticPath)中staticPath被值赋予"${sba.static.path:''}",说明staticPath从配置文件中取值。 以上就是SpringBoot2.0设置静态文件路径的几种方法,你可以根据实际的需求来选择适应的方法。无论使用哪种方法,只要你设置正确,就可以在应用中使用静态资源

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君哥聊编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值