亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問springMVC怎么設置全局檢查是否登錄?

請問springMVC怎么設置全局檢查是否登錄?

LEATH 2019-03-01 10:27:48
@RequestMapping("/admin") public String index(ModelMap modelMap,HttpServletRequest req,HttpSession httpSession){ String basePath = getBasePath(req); modelMap.put("basePath",basePath); modelMap.put("adminPath", basePath+"admin/"); modelMap.put("staticPath", basePath+"static/admin/common"); if(httpSession.getAttribute("admin") == null) { return "redirect:/admin/login"; } modelMap.put("admin", (Admin)httpSession.getAttribute("admin")); return "admin/index"; } /admin/index/admin/info/admin/page/admin/list/admin/table/admin/contact/admin/products/admin/add/admin/delete/admin/get現在有好多controller需要加上用戶是否登錄,代碼如下: if(httpSession.getAttribute("admin") == null) { return "redirect:/admin/login"; } 難道只能一個一個加這段代碼嗎?
查看完整描述

2 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

可以使用Spring MVC 中的攔截器,
攔截的URL pattern 為 /admin/*

xml 配置

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/admin/*" />
        <bean class="me.youname.project.AdminLoginIntercepror">
        </bean>
    </mvc:interceptor>
</mvc:interceptors>
public class AdminLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("admin") == null) {
            // 攔截,重定向到登陸頁面
            response.sendRedirect("/admin/login.html");
            return false;
        }
        // 返回true,表示不攔截
        return true;
    }

    @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 {

    }
}
查看完整回答
反對 回復 2019-03-01
  • 2 回答
  • 0 關注
  • 628 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號