使用场景:在Sevice层或者静态工具类里面需要获取request、session、response这些对象,又不想通过方法传参的方式获取,就可以通过下面的工具类直接获取
POM文件中导入依赖
<!-- hutool工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.21</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
工具类代码
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
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.Optional;
/**
* Servlet工具类
*
* @Author: hanYong
* @CreateTime: 2019-08-28
*/
public class ServletUtil {
/**
* 请求格式为json
*/
private static final String APPLICATION_JSON = "application/json";
/**
* 请求格式为xml
*/
private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
/**
* json后缀
*/
private static final String JSON_SUFFIX = ".json";
/**
* xml后缀
*/
private static final String XML_SUFFIX = ".xml";
/**
* 获取request
*
* @return HttpServletRequest
*/
public static HttpServletRequest getRequest() {
return Optional.ofNullable(getRequestAttributes()).map(ServletRequestAttributes::getRequest).orElse(null);
}
/**
* 获取response
*
* @return HttpServletResponse
*/
public static HttpServletResponse getResponse() {
return Optional.ofNullable(getRequestAttributes()).map(ServletRequestAttributes::getResponse).orElse(null);
}
/**
* 获取session
*
* @return session
*/
public static HttpSession getSession() {
return Optional.ofNullable(getRequest()).map(HttpServletRequest::getSession).orElse(null);
}
/**
* 获取sessionId
*
* @return sessionId
*/
public static String getSessionId() {
return Optional.ofNullable(getSession()).map(HttpSession::getId).orElse(null);
}
/**
* 设置属性(会话级别)
*
* @param key 键
* @param value 值
*/
public static void setSessionAttribute(String key, Object value) {
Optional.ofNullable(getSession()).ifPresent(httpSession -> httpSession.setAttribute(key, value));
}
/**
* 设置属性(会话级别)
*
* @param key1 键
* @param value1 值
* @param key2 键
* @param value2 值
*/
public static void setSessionAttribute(String key1, Object value1, String key2, Object value2) {
Optional.ofNullable(getSession()).ifPresent(httpSession -> {
httpSession.setAttribute(key1, value1);
httpSession.setAttribute(key2, value2);
});
}
/**
* 设置属性(会话级别)
*
* @param key1 键
* @param value1 值
* @param key2 键
* @param value2 值
* @param key3 键
* @param value3 值
*/
public static void setSessionAttribute(String key1, Object value1, String key2, Object value2, String key3, Object value3) {
Optional.ofNullable(getSession()).ifPresent(httpSession -> {
httpSession.setAttribute(key1, value1);
httpSession.setAttribute(key2, value2);
httpSession.setAttribute(key3, value3);
});
}
/**
* 设置属性(请求级别)
*
* @param key 键
* @param value 值
*/
public static void setRequestAttribute(String key, Object value){
Optional.ofNullable(getRequest()).ifPresent(httpServletRequest -> httpServletRequest.setAttribute(key, value));
}
/**
* 设置属性(请求级别)
*
* @param key1 键
* @param value1 值
* @param key2 键
* @param value2 值
*/
public static void setRequestAttribute(String key1, Object value1, String key2, Object value2){
Optional.ofNullable(getRequest()).ifPresent(httpServletRequest -> {
httpServletRequest.setAttribute(key1, value1);
httpServletRequest.setAttribute(key2, value2);
});
}
/**
* 设置属性(请求级别)
*
* @param key1 键
* @param value1 值
* @param key2 键
* @param value2 值
* @param key3 键
* @param value3 值
*/
public static void setRequestAttribute(String key1, Object value1, String key2, Object value2, String key3, Object value3){
Optional.ofNullable(getRequest()).ifPresent(httpServletRequest -> {
httpServletRequest.setAttribute(key1, value1);
httpServletRequest.setAttribute(key2, value2);
httpServletRequest.setAttribute(key3, value3);
});
}
/**
* 获取Attributes
*
* @return ServletRequestAttributes
*/
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
/**
* 是否是Ajax异步请求
*
* @return boolean
*/
public static boolean isAjaxRequest() {
return isAjaxRequest(getRequest());
}
/**
* 是否是Ajax异步请求
*
* @param request 客户端请求
* @return boolean
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.contains(APPLICATION_JSON)) {
return true;
}
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.contains(XML_HTTP_REQUEST)) {
return true;
}
String uri = request.getRequestURI();
if (inStringIgnoreCase(uri, JSON_SUFFIX, XML_SUFFIX)) {
return true;
}
String ajax = request.getParameter("__ajax");
return inStringIgnoreCase(ajax, "json", "xml");
}
/**
* 是否包含字符串(不区分大小写)
*
* @param str 验证字符串
* @param searchStrings 字符串组
* @return boolean
*/
public static boolean inStringIgnoreCase(String str, String... searchStrings) {
if (str != null && searchStrings != null) {
for (String s : searchStrings) {
if (str.equalsIgnoreCase(s == null ? null : s.trim())) {
return true;
}
}
}
return false;
}
/**
* 生成一个重定向URL
*
* @param url 要重定向的URL
* @return 包含 "redirect:" 前缀的重定向URL
*/
public static String redirect(String url) {
return "redirect:" + url;
}
/**
* 生成一个转发URL
*
* @param url 要转发的URL
* @return 包含 "forward:" 前缀的转发URL
*/
public static String forward(String url) {
return "forward:" + url;
}
/**
* 重定向
*
* @param url 重定向地址
*/
@SneakyThrows
public void sendRedirect(String url) {
getResponse().sendRedirect(url);
}
/**
* 转发
*
* @param path 转发地址
*/
@SneakyThrows
public static void sendForward(String path) {
HttpServletRequest request = getRequest();
HttpServletResponse response = getResponse();
request.getRequestDispatcher(path).forward(request, response);
}
@SneakyThrows
public static void responseJson(Object obj){
HttpServletResponse response = getResponse();
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JSONUtil.toJsonStr(obj));
}
}