xiaoxing598
TerrenceTian
采纳率50%
2013-07-12 19:31

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 jacktao219 8年前

    如果是判断是否登录。建议使用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]

    点赞 评论 复制链接分享
  • jinnianshilongnian jinnianshilongnian 8年前

    1、再加一个mvc:exclude-mapping

    2、response.sendRedirect("/login.jsp"); 放到pre中即可,没必要放到post

    3、写一个控制器 转发到jsp即可

    点赞 评论 复制链接分享

相关推荐