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