springboot(八):springboot文件上传、静态资源映射
1.静态资源
2.测试
启动程序后访问:http://localhost:8080/test/img/timg.jpg
3.直接访问
如果直接访问:可以得到图片http://localhost:8080/img/timg.jpg ,但是这样做无疑暴露了真实的地址。
4.定义拦截器拦截/img/*
拦截器代码:
package com.qianliu.springboot_test.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
@Component //@Component标签相当于配置文件中的<bean id="" class=""/>,以后可以直接放入到@Configuration标注的类中
public class SimpleIntercepter implements HandlerInterceptor {
//获取日志
private Logger logger = LoggerFactory.getLogger(this.getClass());
/*
* 进入controller层之前拦截请求
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//含有"/img/"的链接进行拦截
if(request.getRequestURI().startsWith("/img/")){
return false;
}
return true;
}
/*
* 处理请求完成后视图渲染之前的处理操作
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.info("postHandle..................");
}
/*
* 视图渲染之后的操作
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("afterCompletion...............");
}
}
添加拦截器到配置文件中
package com.qianliu.springboot_test.interceptor.configuration;
import com.qianliu.springboot_test.interceptor.SimpleIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/*
* @author qianliu on 2019/5/16 21:43
* @Discription:注册SimpleIntercepter拦截器并注册拦截的url
*/
@Configuration //SimpleIntercepter相当于一个Bean,因为它被@Component标注过
public class UserInterceptorAppConfig implements WebMvcConfigurer {
@Resource
SimpleIntercepter simpleIntercepter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(simpleIntercepter).addPathPatterns("/**"); //该拦截器使用在所有的url上
}
}
5.测试
访问:http://localhost:8080/test/img/timg.jpg
访问:http://localhost:8080/img/timg.jpg