Get HttpServletRequest in Struts 2 interceptor
Asked Answered
B

4

7

To get the HttpServletRequest in an interceptor I used below code:

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

I tried to implement ServletRequestAware in the interceptor but it did not worked.

Are there any better ways to get HttpServletRequest in an Interceptor ?!

Bugaboo answered 8/10, 2013 at 7:24 Comment(2)
Why do you need HttpServletRequest in interceptor?Trait
I want to develop and interceptor which prevents Ajax request from calling directly by url. Please see #14622039. This interceptor will be in interceptor stack which will prevent these requests.Bugaboo
Q
6

The servlet stuff you could get referencing servletConfig interceptor. After this interceptor is invoked you could get servlet stuff from ServletActionContext.

HttpServletRequest request = ServletActionContext.getRequest();
Quarles answered 8/10, 2013 at 8:5 Comment(0)
S
9

You need to use ActionInvocation#getInvocationContext() to retrieve your request.

public String intercept(ActionInvocation invocation) throws Exception {
    ActionContext context = invocation.getInvocationContext();
    HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
    // ...
}
Shellishellie answered 8/10, 2013 at 7:35 Comment(1)
This should be approved answer for using inside interceptor.Trait
Q
6

The servlet stuff you could get referencing servletConfig interceptor. After this interceptor is invoked you could get servlet stuff from ServletActionContext.

HttpServletRequest request = ServletActionContext.getRequest();
Quarles answered 8/10, 2013 at 8:5 Comment(0)
L
1

use

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

it worked for me

Lipoprotein answered 17/3, 2015 at 6:10 Comment(0)
Z
0

you will get ActionInvoction try getInvocationContext() it will return instance of "ActionContext" try .get(HTTP_REQUEST); on this.

or

use

ServletActionContext.getRequest()
Zamia answered 8/10, 2013 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.