2013-10-08 104 views
5

爲了得到HttpServletRequest在我用下面的代碼攔截器:獲取的HttpServletRequest在Struts 2的攔截

HttpServletRequest request =(HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST); 

我試圖實施攔截ServletRequestAware但它並沒有奏效。

有沒有更好的方法在攔截器中獲得HttpServletRequest?!

+0

爲什麼你需要'HttpServletRequest'在攔截? –

+0

我想開發和攔截器,它可以防止由url直接調用Ajax請求。請參閱http://stackoverflow.com/questions/14621539/how-to-determine-whether-a-request-is-ajax-or-normal。 這個攔截器將在攔截器堆棧中,這將阻止這些請求。 –

回答

4

您可以參考的servlet的東西servletConfig攔截器。在這個攔截器被調用後,你可以從ServletActionContext獲得servlet的東西。

HttpServletRequest request = ServletActionContext.getRequest(); 
0

你會得到ActionInvoction試試getInvocationContext()它會返回「ActionContext」的實例試試.get(HTTP_REQUEST);就可以了。

使用

ServletActionContext.getRequest() 
4

您需要使用ActionInvocation#getInvocationContext()檢索您的要求。

public String intercept(ActionInvocation invocation) throws Exception { 
    ActionContext context = invocation.getInvocationContext(); 
    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); 
    // ... 
} 
+1

這應該是批准使用內部攔截器的答案。 –

1

使用

final HttpServletRequest request = (HttpServletRequest) ActionContext.getContext() 
               .get(ServletActionContext.HTTP_REQUEST); 

它爲我工作

+0

這是OP中的代碼。 –

相關問題