springmvc-front.xml
拦截器类
private SessionProvider sessionProvider; private Integer adminId;//管理员,给开发人员用,默认注入adminId=1 //常量 拦截路径规则 private static final String INTERCEPTOR_URL = "/buyer/"; //方法前 /buyer/ //对请求路径 http://localhost:8080/buyer/index.shtml ---- /buyer/ 所请求的方法进行拦截,如果用户没有登录, //不执行后面的方法,如果用户有登录,执行后面的方法 public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub if(adminId != null){ //开发阶段不走正常流程,默认拦截器返回都是true,不走拦截url代码 Buyer buyer = new Buyer(); buyer.setUsername("5201314"); sessionProvider.setAttribute(request, Constans.BUYER_SESSION, buyer,response); }else{ //获取用户是否登录 Buyer buyer = (Buyer) sessionProvider.getAttribute(request, Constans.BUYER_SESSION,response); boolean flag = false;//传给页面,是否隐藏登录 if(null != buyer){ //用户登录的情况 flag = true; } request.setAttribute("isLogin", flag); //请求路径 http://localhost:8080/buyer/index.shtml //getRequestURL()==http://localhost:8080/buyer/index.shtml // getRequestURI()== /buyer/index.shtml String requestURI = request.getRequestURI(); //不是以 INTERCEPTOR_URL为开头的方法都放过,是这开头的,但是用户登录了都放过 if(requestURI.startsWith(INTERCEPTOR_URL)){ //必须登陆 if(null == buyer){ response.sendRedirect("/shopping/login.shtml?returnUrl=" + request.getParameter("returnUrl")); return false;//用户没有登录,方法就不走了,调回登录页面让用户登录 } } } return true; }
流程图