APP请求后台接口,为保证安全性后台在http请求添加cookie并返回APP

这里以登录和退出做例子(简单明了)

 public static void main(HttpServletRequest request,HttpServletResponse response) {
		String JSESSIONID = "111111111111111111";
		String host = request.getServerName(); 
		Cookie cookie = new Cookie("JSESSIONID", JSESSIONID);  
		cookie.setPath("/"); //设置cookie的路径
		cookie.setMaxAge(99999999);  //设置cookie的有效期
		cookie.setDomain(host);//设置访问下的路径带的cookie信息,一般不需要设置
		response.addCookie(cookie); //添加cookie 
}
 public static void main(HttpServletRequest request,HttpServletResponse response) {
    		String cook = SpringContextUtil.getSessionAttribute().toString();
    		Cookie[] cookies = request.getCookies();
    	    for (Cookie cookie : cookies) {
    	      if (cookie.getName().equals("JSESSIONID")) {
    	          cookie.setValue(null);
    	          cookie.setMaxAge(0);// 立即销毁cookie
    	          cookie.setPath("/");
    	          response.addCookie(cookie);
    	          break;
    	      }
    	    }
    	    //如果往session也存入了cookie信息需要删除
    	    request.getSession().removeAttribute("cookie"); 
    }

SpringContextUtil工具类中获取cookie的方法

   public static Object getSessionAttribute(){
        HttpServletRequest request = getRequest();  
        return request == null?null:request.getSession().getAttribute("cookie");  
    } 

   public static HttpServletRequest getRequest(){  
          ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();  
          return requestAttributes==null? null : requestAttributes.getRequest();  
   }

你可能感兴趣的:(APP请求后台接口,为保证安全性后台在http请求添加cookie并返回APP)