加载页面时,cookie在浏览器中添加两次

时间:2018-04-23 07:23:42

标签: spring-mvc cookies

我们正在检查cookie是否存在使用Spring Handler拦截器预处理方法。如果cookie不存在,则使用response.sendRedirect将用户发送到登录状态。如果存在cookie则返回true并且重置cookie时间意味着删除并添加相同的cookie

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream stream = classLoader.getResourceAsStream("bimspring.properties");
        Properties properties = new Properties();
        properties.load(stream);
        String cookieName = properties.getProperty("cookieName", "No Value Found");
        Cookie[] cookies = request.getCookies();
        String rememberMeCookieValue = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase(cookieName))
                    rememberMeCookieValue = cookie.getValue();
            }
        }
        try {
            if (rememberMeCookieValue == null) {
                response.sendRedirect("http://localhost:8080/bimspring/");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

JSP

<% 
 String myCookie = ""; 
        Cookie[] headercookies = request.getCookies();
         for(int i = 0; i < headercookies.length; i++) { 
            Cookie c = headercookies[i];           
            if (c.getName().equals("myCookie")) {
                myCookie = c.getValue();
        }   
        } 
%>  
<%
        if (myCookie.equals(loginWithRememberME)) {

            for (Cookie ck : request.getCookies()) {
                if (ck.getName().equalsIgnoreCase("myCookie")) {
                    ck.setMaxAge(0);
                    response.addCookie(ck);
                }
            }       
             Cookie rememberMeCookie = new Cookie("myCookie", loginWithRememberME);
               rememberMeCookie.setMaxAge(Integer.parseInt(cookieAgeWithRememberME)); 
               response.addCookie( rememberMeCookie ); 
            } 
    if (myCookie.equals(loginWithoutRememberME)) {

     for (Cookie ck : request.getCookies()) {
            if (ck.getName().equalsIgnoreCase("myCookie")) {
                ck.setMaxAge(0);
                response.addCookie(ck);
            }
        } 
     Cookie unRememberMeCookie = new Cookie("myCookie", loginWithoutRememberME);
                   unRememberMeCookie.setMaxAge(Integer.parseInt("500")); 
                   response.addCookie(unRememberMeCookie );
            }
    %>

0 个答案:

没有答案