package com.nbclass.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebUtils {
	
	/**
	 * cookie默认保存时长 （1天）
	 */
	private static final int COOKIE_DEFAULT_MAXAGE = 3600 * 24 * 1;

	
	public static void addCookie(HttpServletResponse response, String name, String value){
		addCookie(response, name, value, COOKIE_DEFAULT_MAXAGE);
	}
	
	public static void addCookie(HttpServletResponse response, String name, String value, int maxage){
		Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxage > 0 ? maxage : COOKIE_DEFAULT_MAXAGE);
        response.addCookie(cookie);
	}
	
	public static String getValueFromCookie(HttpServletRequest request, String cookieName) {
		if(cookieName==null || cookieName.trim().equals(""))return null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie item = cookies[i];
				String name = item.getName();
				if (cookieName.equals(name)) {
					return item.getValue();
				}
			}
		}
		return null;
	}
	
	public static String getReqIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getRemoteAddr();
        }
        if(ip == null){
        	ip = "未知IP";
        }
        return ip;
    }
	
}
