1. 程式人生 > >springmvc與struts2中獲取request物件

springmvc與struts2中獲取request物件

因為框架的不同獲取request物件的方式也會有改變:

springMVC中獲取request的方式有三種:

1.使用註解:

@Autowired
private  HttpServletRequest request;

2.最簡單的方式:引數
@RequestMapping("/test")
@ResponseBody
public void saveTest(HttpServletRequest req, HttpServletResponse resp){
  
}

3. 加入監聽器,然後在程式碼裡面獲取 --在web.xml中配置一個監聽:
<listener>  
        <listener-class>  
            org.springframework.web.context.request.RequestContextListener  
        </listener-class>  
</listener>  

然後在程式碼裡面獲取:
HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
原理:

RequestContextListener實現了 ServletRequestListener ,在其覆蓋的requestInitialized(ServletRequestEvent requestEvent)方法中,將request最終設定到了RequestContextHolder中.


public class RequestContextListener implements ServletRequestListener {

    private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =
            RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";


    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
            throw new IllegalArgumentException(
                    "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
        }
        HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();//從事件物件中獲取request物件
ServletRequestAttributes attributes = new ServletRequestAttributes(request);//將request設定到servletRequestAttributes中 request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);//反過來將servletRequestAttributes設定到request中 LocaleContextHolder.setLocale(request.getLocale()); RequestContextHolder.setRequestAttributes(attributes);//再將servletRequestAttributes設定到requestContextHolder中 }

如何在Struts2中獲取request物件:
HttpServletRequest request = ServletActionContext.getRequest();