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条)

报告相同问题?

悬赏问题

  • ¥50 python如何用抖音这个接口输入抖音ID查询用户信息
  • ¥30 关于移动Web网页使用TinyMCE富文本编辑器上传图片后的光标定位、压缩等几个问题如何解决:
  • ¥25 activeMq在同服务器centos8下消费很慢
  • ¥20 为什么zynq CAN IP 无法进入config配置模式,XCan_SelfTest函数失效?
  • ¥15 Pycharm中程序直接运行可以但进入调试报错
  • ¥15 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥15 我的显卡支持CUDA最高版本是12.3,这个版本也支持VS 2022 17.0这种情况下如果我想下载CUDA11.8,需要下载旧版本的VS2022吗
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!