请问springMVC怎么设置全局检查是否登录?

@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";
        }

难道只能一个一个加这段代码吗?

LEATH
浏览 606回答 2
2回答

largeQ

可以使用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 { } }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java