@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 {
}
}
添加回答
举报
0/150
提交
取消