JAVA工具类获取HttpServletRequest、HttpServletResponse 对象
添加依赖
<!-- Spring Web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.12.RELEASE</version> </dependency> <!-- Java Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
ServletUtils.java
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * 工具类 * */ public class ServletUtils { /** * 获取String参数 * @param name 参数名 */ public static String getParameter(String name) { return getRequest().getParameter(name); } /** * 获取request */ public static HttpServletRequest getRequest() { try { return getRequestAttributes().getRequest(); } catch (Exception e) { return null; } } /** * 获取response */ public static HttpServletResponse getResponse() { try { return getRequestAttributes().getResponse(); } catch (Exception e) { return null; } } /** * 获取session */ public static HttpSession getSession() { return getRequest().getSession(); } public static ServletRequestAttributes getRequestAttributes() { try { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); return (ServletRequestAttributes) attributes; } catch (Exception e) { return null; } } /** * 获取请求头所有数据 * @param request * @return */ public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); if (enumeration != null) { while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } } return map; } }
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)