springboot實現自定義的Interceptor攔截器
阿新 • • 發佈:2019-01-01
構建springboot專案
這裡使用的是eclipse,簡單化 其他實體之類的程式碼省略
專案程式碼
application.properties
# 資料來源配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/cloud?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource .driver-class-name=com.mysql.jdbc.Driver
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId >mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId >
<scope>test</scope>
</dependency>
<!-- 資料庫連線池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
自定義的Interceptor
/**
* 自定攔截器實現HandlerInterceptor介面
* 重寫這幾個方法,在preHandle方法中加入自己的
* 邏輯程式碼
* @author lx
*
*/
public class LoginInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
if(request.getSession().getAttribute("loginUser")!=null) {
return true;
}
response.sendRedirect("/user/login");
return false;
}
}
加入到springboot配置中
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 繼承於WebMvcConfigurerAdapter 重寫它的addInterceptors方法
* 將自定義的Interceptor加入
* @author lx
*
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/*");
}
}