您的位置:首页 > 编程语言 > Java开发

在springboot项目中使用拦截器

2018-05-24 15:49 267 查看

最近练习了springboot项目,作为java开发人员,拦截器是必不可少的,我们用到的最多的用途就是进行用户登录状态的拦截,日志的拦截等。在此记录一下。

首先springboot项目集成了springmvc框架,我使用到的也是springmvc框架的拦截器。

创建一个URLInterceptor类实现HandlerInterceptor,代码如下:
/**
* 拦截器拦截请求
*/

import com.springboot.first.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//重写方法中内容根据具体项目来
public class URLInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String uri = request.getRequestURI();
if(uri.contains("wechat")||uri.contains("api")||uri.contains("wxuser")){
return true;
}
User user = (User)request.getSession().getAttribute("user");
if(!uri.contains("login")){
if(user==null){
response.sendRedirect("/user/tologin");
return false;
}
}else{
if(user!=null){
response.sendRedirect("/main/index");
return false;
}
}
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
if (modelAndView != null){
if(! (modelAndView.getView() instanceof RedirectView)){
String basePath = request.getContextPath();
//modelAndView.addObject("basePath",basePath);
request.setAttribute("basePath",basePath);
}
}
}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}
}
然后将URLInterceptor拦截器添加到springboot的配置中,代码如下:
import com.springboot.first.interceptor.URLInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
* Title:
* @author: chenmingyue
* @date: 2018/3/16 12:01
* Description:配置URLInterceptor拦截器,以及拦截路径
*/
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new URLInterceptor()).addPathPatterns("/*/*");
super.addInterceptors(registry);
}
}
在ssm项目中也可通过xml配置URLInterceptor拦截器,具体配置在spring-mvc.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.springboot.first.interceptor.URLInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: