springboot入门(二)

springboot 专栏收录该内容
4 篇文章 0 订阅

SpringBoot

springboot中的静态资源

  • 在传统的springmvc中的静态资源
    <!--过滤静态资源-->
    <mvc:resources location="/static/css/" mapping="/static/css/**" />
    <mvc:resources location="/static/image/" mapping="/static/image/**" />
    <mvc:resources location="/static/js/" mapping="/static/js/**" />
    <mvc:resources location="/static/font-awesome/" mapping="/static/font-awesome/**" />
  • 因为springboot中连springmvc.xml配置文件都没有所以在springboot中处理静态资源默认的路径是

    • classpath:/META-INF/resources/
    • classpath:/resources/
    • classpath:/static/
    • classpath:/public/

springboot中的拦截器

package cn.springmvc.interceptor;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springboot拦截器:写一个拦截器类实现HandlerInterceptor接口
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置方法正在执行..");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("后置方法正在执行..");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("方法完成执行..");
    }
}

  • 因为在springboot中没有springmvc的配置类所以我们应该写一个配置类来配置拦截器
package cn.springmvc.config;

import cn.springmvc.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置拦截器
 *  1.声明该类是个java配置类
 *  2.实现 WebMvcConfigurer 接口
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**"); //此方法是拦截哪些路径
    }
}

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 1024 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值