栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springmvc的拦截器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springmvc的拦截器

作用:当用户访问某个资源时,我们需要做一些判断,若满足条件,让用户访问资源,若不满足,则跳转到指定页面!

那如何实现呢?

首先新建一个类让其实现HandlerInterceptor,重写方法,在第一个重写的方法也就是

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException 里面做一些判断。满足条件用户可以访问资源,不满足,用户跳转到指定资源。

然后在applicationcontext.xml添加拦截路径,比如:

    
    
        
            
            
        
    

来个具体的代码吧:

package com.imooc.reader.interceptor;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        // 如果是登陆页面则放行

        if (request.getRequestURI().contains("login")) {
            return true;
        }

        HttpSession session = request.getSession();

        // 如果用户已登陆也放行
        if(session.getAttribute("user") != null) {
            return true;
        }

        // 用户没有登陆跳转到登陆页面
        request.getRequestDispatcher("/WEB-INF/ftl/management/login.ftl").forward(request, response);
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

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

    }
}

拦截路径

    
    
        
            
            
        
    

备注一下下,复习个小知识点:获取当前访问时候的uri;

request.getRequestURI()

ok,实现了动态拦截!!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/309437.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号