JAVA工具类如何获取HttpServletRequest和HttpServletResponse对象呢?
下文笔者讲述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; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。