All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.spring.ServletHelp Maven / Gradle / Ivy

There is a newer version: 2023.2.5
Show newest version
package shz.spring;

import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper;
import shz.core.Coder;
import shz.core.NullHelp;
import shz.core.PRException;
import shz.core.hash.MdHash;
import shz.core.io.IOHelp;

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

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public final class ServletHelp {
    private ServletHelp() {
        throw new IllegalStateException();
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes)
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        return null;
    }

    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes)
            return ((ServletRequestAttributes) requestAttributes).getResponse();
        return null;
    }

    public static String getIp(HttpServletRequest request) {
        String ip;
        // X-Forwarded-For:Squid 服务代理
        if (isIp(ip = request.getHeader("X-Forwarded-For"))) return ip0(ip);
        // Proxy-Client-IP:apache 服务代理
        if (isIp(ip = request.getHeader("Proxy-Client-IP"))) return ip0(ip);
        // WL-Proxy-Client-IP:weblogic 服务代理
        if (isIp(ip = request.getHeader("WL-Proxy-Client-IP"))) return ip0(ip);
        // HTTP_CLIENT_IP:有些代理服务器
        if (isIp(ip = request.getHeader("HTTP_CLIENT_IP"))) return ip0(ip);
        // X-Real-IP:nginx服务代理
        if (isIp(ip = request.getHeader("X-Real-IP"))) return ip0(ip);
        return ip0(request.getRemoteAddr());
    }

    private static boolean isIp(String ip) {
        return ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip);
    }

    private static String ip0(String ip) {
        int idx = ip.indexOf(",");
        if (idx != -1) ip = ip.substring(0, idx);
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    public static UserAgent getUserAgent(HttpServletRequest request) {
        return UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    }

    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("Accept");
        if (header != null && header.toLowerCase().contains("application/json")) return true;
        header = request.getHeader("X-Requested-With");
        //XMLHttpRequest
        return header != null && header.toLowerCase().contains("xmlhttprequest");
    }

    public static String getBody(HttpServletRequest request) {
        if (request == null) return null;
        if (request instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) request;
            try {
                return new String(requestWrapper.getContentAsByteArray(), requestWrapper.getCharacterEncoding());
            } catch (UnsupportedEncodingException e) {
                throw PRException.of(e);
            }
        }
        try {
            String enc = request.getCharacterEncoding();
            Charset cs = enc == null ? StandardCharsets.ISO_8859_1 : Charset.forName(enc);
            return IOHelp.read(IOHelp.newBufferedReader(request.getInputStream(), cs));
        } catch (IOException e) {
            throw PRException.of(e);
        }
    }

    public static String getKey(HttpServletRequest request, String key) {
        String value = request.getHeader(key);
        if (NullHelp.nonBlank(value)) return value;
        String queryString = request.getQueryString();
        if (NullHelp.nonBlank(queryString)) {
            String[] array = queryString.split("&");
            for (String s : array)
                if (s.startsWith(key) && s.charAt(key.length()) == '=') return s.substring(key.length() + 1);
        }
        Cookie[] cookies = request.getCookies();
        if (NullHelp.nonEmpty(cookies))
            for (Cookie cookie : cookies) if (cookie.getName().equals(key)) return cookie.getValue();
        return null;
    }

    public static String identity(HttpServletRequest request) {
        if (request == null) return null;
        String body = null;
        if (request instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) request;
            body = Coder.hexEncode(MdHash.MD5.hash(requestWrapper.getContentAsByteArray()));
        } else try {
            body = Coder.hexEncode(MdHash.MD5.hash(request.getInputStream()));
        } catch (IOException ignored) {
        }
        return Coder.hexEncode(MdHash.MD5.hash((request.getServletPath() + ":" + request.getMethod() + ":" + body).getBytes()));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy