springboot之mvc

2023-01-28  本文已影响0人  sunpy

springboot配置静态资源


通过springboot的路径映射来访问本地的资源
application.yml:

resource:
  root:
    location: E://resource

实现WebMvcConfigurer中的addResourceHandlers方法:

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Value("${resource.root.location}")
    private String resRootLocation;

    /**
     * 配置静态资源映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**")
                .addResourceLocations("file:///" + resRootLocation + "/");
    }
}

springboot实现拦截器


// 自定义拦截器
@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String point = request.getParameter("point");
        log.info("=========" + point);

        if (Objects.equals(point, "1")) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        return false;
    }
}

// 添加拦截器
@Slf4j
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/test/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
上一篇下一篇

猜你喜欢

热点阅读