首页  

springboot2获取HttpServletRequest的三种方式     所属分类 spring 浏览量 1403
1 作为 controller 的成员变量自动注入
2 作为方法参数 自动绑定
3 RequestContextHolder 中获取

@RestController
public class InfoController {
	@Autowired
	private HttpServletRequest requestField;
	
	
        @RequestMapping("/requestInfo")
	public Map requestInfo(HttpServletRequest requestParam) throws Exception{
		Map map = new HashMap();
		
	        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
	        HttpServletRequest request = servletRequestAttributes.getRequest();
	    
	        map.put("requestField", requestField.toString());
	        map.put("request", request.toString());
	        map.put("requestParam", requestParam.toString());
	        map.put("requestFieldClass", requestField.getClass());

	        Object proxyTarget = AopUtil.getTarget(requestField);	    
	        map.put("proxyTargetClass", proxyTarget.getClass());
	        map.put("proxyTarget", proxyTarget.toString());
	
		return map;
	}
}



	
	
{
    "requestFieldClass": "com.sun.proxy.$Proxy89",
    "request": "org.apache.catalina.connector.RequestFacade@2c59094f",
    "requestField": "Current HttpServletRequest",
    "proxyTargetClass": "org.apache.catalina.connector.RequestFacade",
    "requestParam": "org.apache.catalina.connector.RequestFacade@2c59094f",
    "proxyTarget": "org.apache.catalina.connector.RequestFacade@2c59094f"
}


成员变量 requestField  是 jdk代理对象 ,
其代理的目标对象  proxyTarget   org.apache.catalina.connector.RequestFacade@2c59094f
 
这三种方式 获取到的最终对象 都指向同一个 
org.apache.catalina.connector.RequestFacade@2c59094f

这三种方式是等价的

	
获取 jdk代理的目标对象

	private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
		Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
		h.setAccessible(true);
		Object object = h.get(proxy);
		
		Field objectFactoryField = object.getClass().getDeclaredField("objectFactory");
		objectFactoryField.setAccessible(true);

		Object objectFactoryObject = objectFactoryField.get(object);
		ObjectFactory objectFactory = (ObjectFactory) objectFactoryObject;

		return objectFactory.getObject();
	}

上一篇     下一篇
maven内置属性

springboot中为什么不推荐使用jsp

Maven Dependencies 与 Referenced Libraries的区别

21 Questions for a Trading Plan

科创板要点

aerospike增加节点