TerrenceTian 2013-07-12 19:31 采纳率: 0%
浏览 913
已采纳

springMVC 拦截器如何做登录检查及页面跳转

一个非常简单的登录权限拦截器

问题一:登录页面的提交请求肯定是要过滤掉的,目前采用在xml里配置<mvc:mapping path="/supplier/*"/>来过滤,可不可以配置不拦截某种请求。如果是按目前这种配置需要拦截请求,当请求太多的时候那就太麻烦了。

问题二:我简单地在拦截器里判断session是否有值,如果有表示登录,如果没有则跳转登录页面。按我下面的做法是不行的,有没有正确而有效的方法。

问题三:如果大家能够给出在拦截器内跳转页面的方案,可我的login.jsp是放在WEB-INF下面的,通过ModelAndView跳转时,视图解析器会跳转到/WEB-INF/login.jsp下,那肯定是找不到页面的。但如果我放到此文件夹下,那浏览器又不能访问login.jsp页面了。

 

public class UserInterceptor implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object obj, Exception err)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object obj, ModelAndView mav) throws Exception {
        response.sendRedirect("/login.jsp");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object obj) throws Exception {
        String str = (String) request.getSession().getAttribute("isLogin");
        System.out.println("str=========>"+str);
        if(str!=null){
            return true;
        }
        return false;
    }
}
<!-- 自定义拦截链配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/supplier/*"/>
            <mvc:mapping path="/goods/*"/>
            <mvc:mapping path="/contact/*"/>
            <bean class="com.xiaoxing.shangjia.user.controller.UserInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
  • 写回答

2条回答 默认 最新

  • jacktao219 2013-07-13 11:19
    关注

    如果是判断是否登录。建议使用filter [code="java"]package com.ccsu.common.filter;

    import com.ccsu.common.constants.SessionConstants;
    import com.ccsu.entity.userSystem.User;
    import com.ccsu.util.userSystem.ProsReader;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.http.HttpStatus;
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;

    /**

    • Created with IntelliJ IDEA.
    • User: Ambitor springMVC拦截器 判断session中用户是否过期
    • Date: 13-6-27
    • Time: 下午7:31
    • To change this template use File | Settings | File Templates. *
    • @author 罗涛 */

    public class SystemFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(SystemFilter.class);
    
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
            throw new ServletException("OncePerRequestFilter just supports HTTP requests");
        }
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpRequest.getSession(true);
    
        StringBuffer url = httpRequest.getRequestURL();
        String[] strs = ProsReader.getString("INDICATION_APP_NAME").split("\\|");
        if (strs != null && strs.length > 0) {
            for (String str : strs) {
                if (url.indexOf(str) >= 0) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        Object object = session.getAttribute(SessionConstants.SESSION_USER);
        User user = object == null ? null : (User) object;
        if (user == null) {
            boolean isAjaxRequest = isAjaxRequest(httpRequest);
            if (isAjaxRequest) {
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.sendError(HttpStatus.UNAUTHORIZED.value(),
                        "您已经太长时间没有操作,请刷新页面");
            }
            httpResponse.sendRedirect("/page/login/user_login");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    
    /**
     * 判断是否为Ajax请求
     *
     * @param request HttpServletRequest
     * @return 是true, 否false
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return request.getRequestURI().startsWith("/api");
    

    // String requestType = request.getHeader("X-Requested-With");
    // return requestType != null && requestType.equals("XMLHttpRequest");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
            /*如果需要注入,请取消注释*/
    

    // ServletContext servletContext = filterConfig.getServletContext();
    // WebApplicationContext applicationContext = (WebApplicationContext) servletContext.
    // getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    // if (null == topConstantsImpl) {
    // //从Spring AC 中加载app configuration对象
    // topConstantsImpl = applicationContext.getBean(TopConstantsImpl.class);
    // }
    }

    @Override
    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.
    }
    

    }
    [/code]

    [code="java"] <!--<!– 判断用户session 是否过期,如果过期,让用户重新登录–>-->
    <!---->
    <!--SystemFilter-->
    <!--com.yitaosoft.common.filter.SystemFilter-->
    <!---->
    <!---->
    <!--SystemFilter-->
    <!--/*-->
    <!---->[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单纯型python实现编译报错
  • ¥15 c++2013读写oracle
  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音