1.修改端口号:
在application.properties中添加如下配置即可:
XML
server.port=8088
2.静态资源访问:
首先打开ResourceProperties这个类的源码:
将静态资源放到类中默认位置即可实现访问:
http://localhost:8088/erth.jpg
3.拦截器:
先定义个拦截器:
java
package com.lxj.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
private Logger logger=LoggerFactory.getLogger(LoginInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler){
logger.debug("执行前!");
return true;
}
@Override
public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView){
logger.debug("执行后!");
}
@Override
public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex){
logger.debug("跳转后!");
}
/*
* 这里注意日志级别,默认显示info以上级别,如果显示更低级别需要在配置文件中配置 logging.level.com.lxj=debug */
}
然后通过实现WebMvcConfigure并添加@Configuration注解来实现自定义拦截器:
java
package com.lxj.config;
import com.lxj.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Bean //将LoginInterceptor拦截器注入到spring容器中
public LoginInterceptor loginInterceptor(){
return new LoginInterceptor();
}
@Override //重写接口方法,添加自定义拦截器
public void addInterceptors(InterceptorRegistry registry){
// registry注册拦截器
// addPathPatterns添加拦截路径:
// '?' 匹配任何单字符
// '*' 匹配0或者任意数量字符
// '**' 匹配0或者更多目录
registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/**");
}
}
重新访问可以发现已执行对应的拦截器:
可以发现比之前的spring繁琐的配置文件方便多了!