编程知识 cdmana.com

SpringMVC中静态获取request对象 Spring中获取 HttpServletRequest对象

  SpringMVC中静态获取request对象 Spring中获取 HttpServletRequest对象

 

一、web.xml 中配置Listener

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
</listener>

二、代码实现

1、创建RequestUtil 静态获取request、response对象

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * description: 静态获取request、response对象
 * @version v1.0
 * @author w
 * @date 2020年6月23日下午3:23:58
 **/
public class RequestUtil {
	
	/**
	 * description: 静态获取request对象
	 * @return HttpServletRequest
	 * @version v1.0
	 * @author w
	 * @date 2020年6月23日 下午3:39:43
	 */
	public static HttpServletRequest getRequest() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();
		return request ;
	}

	/**
	 * description: 静态获取response 对象
	 * @return HttpServletResponse
	 * @version v1.0
	 * @author w
	 * @date 2020年6月23日 下午3:40:02
	 */
	public static HttpServletResponse getResponse() {
		ServletWebRequest servletWebRequest = (ServletWebRequest)RequestContextHolder.getRequestAttributes();
		HttpServletResponse response = servletWebRequest.getResponse();
		return response;
	}
	
}

 

更多: WebService获取request对象

 

 

版权声明
本文为[HaHa_Sir]所创,转载请带上原文链接,感谢
https://thinkcode.blog.csdn.net/article/details/106925284

Scroll to Top