springboot实现拦截器,监听器,过滤器

项目总结:

  在项目的过程中,用到了那三个东西。

我用拦截器实现了未登录用户的拦截,将未登录用户请求的地址转到登录的页面。

我用过滤器实现了请求中数据的编码集的设置。

我用监听器实现了从websocket中获取HttpSession,关于这个功能详见:

https://www.cnblogs.com/1998xujinren/p/12340671.html

 

  

 

上图说明了过滤器(filter)的范围比拦截器(interceptor)的范围广。filter是依赖Servlet容器的。而拦截器是依赖springmvc的。

过滤器是函数调用实现的。拦截器是通过动态代理实现的。

现在看看实现,以下实现都是在springboot上面的。

MyFilter:

package news.listener;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.stereotype.Component;

/**
 * 过滤器,每一次的url处理请求都要经过这里,可以处理这个数据传输中的编码问题
 * @author 徐金仁
 */
@Component
public class MyFilter implements Filter{
    String charSet = "utf-8";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
            throws IOException, ServletException {
        //处理数据传过来的编码
        String cha = request.getCharacterEncoding();
        if(!cha.equalsIgnoreCase(charSet)){
            request.setCharacterEncoding(charSet);
        }
        cha = response.getCharacterEncoding();
        if(!cha.equalsIgnoreCase(charSet)){
            response.setCharacterEncoding(charSet);
        }
        filter.doFilter(request, response);
    }
    
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    
    @Override
    public void destroy() {
    }
}


MyInterceptor :
package news.listener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import news.bean.UserInfo;
import news.utils.StaticValue;
/**
 * 拦截器,
 * @author 徐金仁
 */
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 在进入controller里面之前调用该方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Object obj = request.getSession().getAttribute(StaticValue.CURRENT_USER);
        //获取从项目名开始到最后的字符的url地址
        String path = request.getRequestURI();
        if(obj == null){//说明是没有登录的,那就跳到登录界面去登录吧
            //将login.html的跳转和里面页面的请求解放出来,将处理找回密码的页面解放出来,将注册页面解放出来
            if(path.indexOf("/login/") >= 0 || path.indexOf("/retrieve/") > 0 || path.indexOf("/acc/")  > 0 || path.indexOf("register") > 0){
                return HandlerInterceptor.super.preHandle(request, response, handler);
            }
            response.sendRedirect("/newsinfo2/login/login.html");
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
    /**
     * 在进入controller之后(Controller方法之后),但是在视图渲染之前调用,
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    
    /**
     * 在视图渲染之后调用
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

 

配置项:

NewsConfig :
package news.config;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import news.listener.MyFilter;
import news.listener.MyInterceptor;
/**
 * 配置类
 * @author 徐金仁
 */
@Configuration
public class NewsConfig implements WebMvcConfigurer{
    
    @Resource
    private MyFilter myFilter;
    
    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excuteList = new ArrayList<String>();
        excuteList.add("/js/*");
        excuteList.add("/bootstrap/**");
        excuteList.add("/static/*");
        excuteList.add("/images/*");
        excuteList.add("/persionImages/*");
        excuteList.add("/css/*");
        excuteList.add("/bootstrap/js/*");
        //添加自定义的拦截器之后要除去静态资源,也就是说解放静态资源
        registry.addInterceptor(new MyInterceptor()).excludePathPatterns(excuteList);
    }
    
    
    
    @SuppressWarnings("unchecked")
    @Bean
    public FilterRegistrationBean testFilterRegistration(){
        FilterRegistrationBean filter = new FilterRegistrationBean(myFilter);
        filter.setName("myFilter");
        filter.setOrder(1);
     //设置拦截路径 filter.addUrlPatterns(
"/*"); return filter; } }

 

监听器:

MyListener :
package news.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

/**
 * 监听器,用于监听每一次的请求,并获取配置好httpsession
 * @author 徐金仁
 *
 */
@WebListener
public class MyListener implements ServletRequestListener {
    
    /**
     * request创建时监听
     */
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
          //将所有request请求都携带上httpSession
        ((HttpServletRequest)sre.getServletRequest()).getSession();
    }
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
    }
    
    public MyListener() {
    }
    
}

 

 

 

 

相关博客收藏:

https://blog.csdn.net/baidu_20876831/article/details/80405515

https://blog.csdn.net/u014338530/article/details/86510568

https://www.cnblogs.com/faster/p/10979856.html

 

posted @ 2020-02-24 16:55  陆某人  阅读(399)  评论(0编辑  收藏  举报