1. 程式人生 > >SSM框架項目的mvc攔截器

SSM框架項目的mvc攔截器

contex redirect del return exception http user 建立 use

為了防止用戶在不登錄的情況下通過並接請求直接訪問系統,我們需要通過session和攔截器來防止這樣的情況。

攔截器的配置:

為攔截器建立一個包:interceptor,並在包裏建立 LoginInterceptor 攔截器類

技術分享圖片

攔截器需要 implements HandlerInterceptor,並實現 HandlerInterceptor 的方法:

/**
 * 登錄攔截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean
preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { HttpSession session = httpServletRequest.getSession(); if ( session.getAttribute("LOGIN_USER") != null ){ return true; }else { httpServletResponse.sendRedirect( httpServletRequest.getContextPath()
+ "/gradu/dologin"); return false; } } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws
Exception { } }

配置spring-mvc文件:

<!--攔截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/gradu/dologin" />
            <bean class="com.hwl.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

註意:

<mvc:mapping path="/**"/> 是已經攔截了所有請求,包括登錄,

如果後來想不攔截某個頁面,就添加:<mvc:exclude-mapping path="/system/login" />

另外。記得登錄時添加session。

SSM框架項目的mvc攔截器