欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cookie设置

程序员文章站 2022-05-24 14:38:06
...

1.写入cookie

        HttpServletResponse response = ServletUtils.getResponse();        
        // 将token设置到cookie 返回
        Cookie cookie = new Cookie(Constants.HEADER_ACCESS_TOKEN_KEY, tokenVo.getToken());
        cookie.setPath("/");
        //设置cookie的有效时长为100天,默认关闭浏览器失效,单位为:秒
        cookie.setMaxAge(100*24*60*60);
        response.addCookie(cookie);

2.获取cookie

public class getCookie(HttpServletRequest request){
       Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new ServiceException(ErrorCode.authority_un_login.getCode(),
                        ErrorCode.authority_un_login.getMessage());
          }
          for (Cookie cookie : cookies) {
               if (Constants.HEADER_ACCESS_TOKEN_KEY.equals(cookie.getName())) {
                  token = cookie.getValue();
               }
               if (Constants.HEADER_COOKIE_FRANCHISEE_ID.equals(cookie.getName())) {
                    franchiseeId = cookie.getValue();
           }
       }
}

3.工具类

@Slf4j
public class ServletUtils {

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * heafer中获取User-Agent参数
     *
     * @return
     */
    public static String getUserAgent() {
        HttpServletRequest request = getRequest();
        return request.getHeader(Constants.HEADER_USER_AGENT);
    }

    /**
     * heafer中获取User-Agent参数
     *
     * @param request
     * @return
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader(Constants.HEADER_USER_AGENT);
    }

    /**
     * 获取root url全路径
     *
     * @return
     */
    public static String getRootUrl() {
        HttpServletRequest request = getRequest();
        return getRootUrl(request);
    }

    /**
     * 获取root url全路径
     *
     * @return
     */
    public static String getRootUrl(HttpServletRequest request) {
        // 全url地址
        StringBuffer url = request.getRequestURL();
        String uri = request.getRequestURI();
        StringBuffer buffer = url.delete(url.length() - uri.length(), url.length());
        return buffer.toString();
    }

    /**
     * 获取访客xff地址, 如果通过代理进来, 则透过防火墙获取真实xff地址;
     *
     * @return
     */
    public static String getIpAddr() {
        HttpServletRequest request = getRequest();
        return getIpAddr(request);
    }

    /**
     * 获取访客xff地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String xff = request.getHeader("x-forwarded-for");

        if (xff == null || xff.length() == 0 || "unknown".equalsIgnoreCase(xff)) {
            if (xff == null || xff.length() == 0 || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("Proxy-Client-xff");
            }
            if (xff == null || xff.length() == 0 || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("WL-Proxy-Client-xff");
            }
            if (xff == null || xff.length() == 0 || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("HTTP_CLIENT_xff");
            }
            if (xff == null || xff.length() == 0 || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (xff == null || xff.length() == 0 || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getRemoteAddr();
            }
        } else if (xff.length() > 15) {
            String[] xffArray = xff.split(",");
            for (String str : xffArray) {
                if (!("unknown".equalsIgnoreCase(str))) {
                    xff = str;
                    break;
                }
            }
        }
        return xff;
    }

    /**
     * 输出到页面上
     * @param msg
     */
    public static void println(String msg) {
        PrintWriter writer = null;
        try {
            HttpServletResponse response = getResponse();
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Cache-Control", "no-store");
            writer = response.getWriter();
            writer.println(msg);
        } catch (Exception e) {
            log.error("writer to body error...", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }

}