为了账号安全,请及时绑定邮箱和手机立即绑定

请问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条经验 获得超7个赞

可以使用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 关注
  • 605 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信