HttpServletRequest类常见API

  • javax.servlet.http.HttpServletRequest与HttpServletResponse类解析
  1. /**
  2. * Copyright (c) bigbeardhk@163.com Corporation 2022. All Rights Reserved.
  3. */
  4. package com.hk.study.controller;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import javax.servlet.http.Cookie;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;
  13. import java.util.Enumeration;
  14. import java.util.Map;
  15. /**
  16. * @Author : bigbeardhk
  17. * @Date : 2022/06/04 21:12
  18. **/
  19. @RestController
  20. @RequestMapping("/httpServlet")
  21. public class HttpServletController {
  22. @GetMapping("/testRequest/{id}")
  23. public String testRequest(HttpServletRequest request, HttpServletResponse response) {
  24. StringBuffer requestURL = request.getRequestURL(); // http://localhost:8081/httpServlet/testRequest/654
  25. String queryString = request.getQueryString(); // ?后面的地址参数 test=test-51gjie&u2=u2-51gjiet
  26. Map<String, String[]> parameterMap = request.getParameterMap(); // ?后面的参数和请求体里面的参数
  27. Cookie[] cookies = request.getCookies();
  28. HttpSession session = request.getSession();
  29. session.setAttribute("sessionname","sessionname");
  30. String jsessionid = (String) session.getAttribute("JSESSIONIDTest");
  31. // ====================response=============================
  32. response.addHeader("token", "dsfsdfsdhthytju"); // 响应头
  33. response.addCookie(new Cookie("myname", session.getId())); // set-cookies
  34. return "helloword";
  35. }
  36. }
/**
 * Copyright (c) bigbeardhk@163.com Corporation 2022. All Rights Reserved.
 */

package com.hk.study.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * @Author : bigbeardhk
 * @Date : 2022/05/03 18:41
 **/
public class AddressUtil {

    /**
     * 获取请求的ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {

                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        return ipAddress;
    }

    /**
     * 获取完整的请求地址
     * @param request
     * @return
     */
    public static String getRequestAddress(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String completeURL = requestURL.toString();
        String queryString = request.getQueryString(); // ?后面的地址参数
        if (StringUtil.isNotEmpty(queryString)) {
            completeURL = completeURL + "?" + queryString;
        }
        return completeURL;
    }
}

image.png
image.png

常见问题

:::info Q :如何生成cookies?
A : 可以在响应时,set-cookies,并为cookies设置过期时间,如果Expires为会话时,说明浏览器一关闭,该cookies就会失效

Q :cookies的跨域区分标准为?
A:协议 + ip + 端口号 ,如https://localhost:8080/

Q :cookies的不可跨域性?
A:可以给cookies设置domain与path参数,记住domain参数必须以点(“.”)开始;path属性需要使用符号“/”结尾

K : JSESSIONID是tomcat容器默认给sessionID,set-cookies的key :::


资料学习与引用