本来地址:Spring Boot干货系列:(六)静态资源和拦截器处理
博客地址:tengj.top/javascript
本章咱们来介绍下SpringBoot对静态资源的支持以及很重要的一个类WebMvcConfigurerAdapter。html
前面章节咱们也有简单介绍过SpringBoot中对静态资源的默认支持,今天详细的来介绍下默认的支持,以及自定义扩展如何实现。java
Spring Boot 默认为咱们提供了静态资源处理,使用 WebMvcAutoConfiguration 中的配置各类属性。
建议你们使用Spring Boot的默认配置方式,提供的静态资源映射以下:git
在工程里面路径是这样:
github
对应的配置文件配置以下:web
# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开复制代码
咱们能够经过修改spring.mvc.static-path-pattern来修改默认的映射,例如我改为/dudu/**,那运行的时候访问 http://lcoalhost:8080/dudu/index.html 才对应到index.html页面。ajax
若是Spring Boot提供的Sping MVC不符合要求,则能够经过一个配置类(注解有@Configuration的类)加上@EnableWebMvc注解来实现彻底本身控制的MVC配置。spring
固然,一般状况下,Spring Boot的自动配置是符合咱们大多数需求的。在你既须要保留Spring Boot提供的便利,有须要增长本身的额外的配置的时候,能够定义一个配置类并继承WebMvcConfigurerAdapter,无需使用@EnableWebMvc注解。编程
这里咱们提到这个WebMvcConfigurerAdapter这个类,重写这个类中的方法可让咱们增长额外的配置,这里咱们就介绍几个经常使用的。json
好比,咱们想自定义静态资源映射目录的话,只需重写addResourceHandlers方法便可。
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
/** * 配置静态访问资源 * @param registry */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
super.addResourceHandlers(registry);
}
}复制代码
经过addResourceHandler添加映射路径,而后经过addResourceLocations来指定路径。咱们访问自定义my文件夹中的elephant.jpg 图片的地址为 http://localhost:8080/my/elephant.jpg
若是你想指定外部的目录也很简单,直接addResourceLocations指定便可,代码以下:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("file:E:/my/");
super.addResourceHandlers(registry);
}复制代码
addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径
之前写SpringMVC的时候,若是须要访问一个页面,必需要写Controller类,而后再写一个方法跳转到页面,感受好麻烦,其实重写WebMvcConfigurerAdapter中的addViewControllers方法便可达到效果了
/** * 之前要访问一个页面须要先建立个Controller控制类,再写方法跳转到页面 * 在这里配置后就不须要那么麻烦了,直接访问http://localhost:8080/toLogin就跳转到login.htm页面了 * @param registry */
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/toLogin").setViewName("login");
super.addViewControllers(registry);
}复制代码
值的指出的是,在这里重写addViewControllers方法,并不会覆盖WebMvcAutoConfiguration中的addViewControllers(在此方法中,Spring Boot将“/”映射至index.html),这也就意味着咱们本身的配置和Spring Boot的自动配置同时有效,这也是咱们推荐添加本身的MVC配置的方式。
拦截器在咱们项目中常用的,这里就来介绍下最简单的判断是否登陆的使用。
要实现拦截器功能须要完成如下2个步骤:
首先,自定义拦截器代码:
package com.dudu.interceptor;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag =true;
User user=(User)request.getSession().getAttribute("user");
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 {
}
}复制代码
这里咱们简单实现了根据session中是否有User对象来判断是否登陆,为空就跳转到登陆页,不为空就经过。
接着,重写WebMvcConfigurerAdapter中的addInterceptors方法以下:
/** * 拦截器 * @param registry */
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/login");
super.addInterceptors(registry);
}复制代码
addPathPatterns("/**")
对全部请求都拦截,可是排除了/toLogin
和/login
请求的拦截。
页面登陆关键代码
//简单登陆操做
$("#doLogin").click(function (e) {
$.ajax({
type : "POST",
url : "/login",
data : {
"userName" : $("#userName").val(),
"password" : $("#password").val()
},
dataType : "json",
success : function(data) {
if (data.result == "1") {
window.location.href ="/learn";
} else {
alert("帐号密码不能为空!");
}
}
});
});复制代码
控制器代码:
package com.dudu.controller;
@Controller
public class LearnController {
/** *登陆操做 **/
@RequestMapping(value = "/login",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> login(HttpServletRequest request, HttpServletResponse response){
Map<String,Object> map =new HashMap<String,Object>();
String userName=request.getParameter("userName");
String password=request.getParameter("password");
if(!userName.equals("") && password!=""){
User user =new User(userName,password);
request.getSession().setAttribute("user",user);
map.put("result","1");
}else{
map.put("result","0");
}
return map;
}
@RequestMapping("/learn")
public ModelAndView index(){
List<LearnResouce> learnList =new ArrayList<LearnResouce>();
LearnResouce bean =new LearnResouce("官方参考文档","Spring Boot Reference Guide","http://docs.spring.io/spring-boot/docs/1.5.1.RELEASE/reference/htmlsingle/#getting-started-first-application");
learnList.add(bean);
bean =new LearnResouce("官方SpriongBoot例子","官方SpriongBoot例子","https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples");
learnList.add(bean);
bean =new LearnResouce("龙国学院","Spring Boot 教程系列学习","http://www.roncoo.com/article/detail/125488");
learnList.add(bean);
bean =new LearnResouce("嘟嘟MD独立博客","Spring Boot干货系列 ","http://tengj.top/");
learnList.add(bean);
bean =new LearnResouce("后端编程嘟","Spring Boot教程和视频 ","http://www.toutiao.com/m1559096720023553/");
learnList.add(bean);
bean =new LearnResouce("程序猿DD","Spring Boot系列","http://www.roncoo.com/article/detail/125488");
learnList.add(bean);
bean =new LearnResouce("纯洁的微笑","Sping Boot系列文章","http://www.ityouknow.com/spring-boot");
learnList.add(bean);
bean =new LearnResouce("CSDN——小当博客专栏","Sping Boot学习","http://blog.csdn.net/column/details/spring-boot.html");
learnList.add(bean);
bean =new LearnResouce("梁桂钊的博客","Spring Boot 揭秘与实战","http://blog.csdn.net/column/details/spring-boot.html");
learnList.add(bean);
bean =new LearnResouce("林祥纤博客系列","从零开始学Spring Boot ","http://412887952-qq-com.iteye.com/category/356333");
learnList.add(bean);
ModelAndView modelAndView = new ModelAndView("/template");
modelAndView.addObject("learnList", learnList);
return modelAndView;
}
}复制代码
这样访问的时候,若是未登陆就会跳转到login.html页面,而访问http://localhost:8080/toLogin 和http://localhost:8080/login 不会被拦截。
静态资源跟拦截器在平时项目中常常用到,弄懂如何处理是颇有用的。今天就到此为止,下一篇未来介绍一下项目中如何使用日志。
想要查看更多Spring Boot干货教程,可前往:Spring Boot干货系列总纲
一直以为本身写的不是技术,而是情怀,一篇篇文章是本身这一路走来的痕迹。靠专业技能的成功是最具可复制性的,但愿个人这条路能让你少走弯路,但愿我能帮你抹去知识的蒙尘,但愿我能帮你理清知识的脉络,但愿将来技术之巅上有你也有我,但愿大爷你看完打赏点零花钱给我。
订阅博主微信公众号:嘟爷java超神学堂(javaLearn)三大好处: