Get HttpServletRequest in Struts 2 interceptor - struts2

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 ?!

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);
// ...
}

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();

use
final HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
.get(ServletActionContext.HTTP_REQUEST);
it worked for me

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

Related

Default Http method used by struts2 for processing request.I am always getting GET

Whenever i am intercepting request in struts2 interceptor getting httpmethod as GET. My requirement is to disable submission with GET httpmethod. please suggest.
try somthing like :
public String intercept(ActionInvocation actionInvocation) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
if (!request.getMethod().equals("POST")){
return Action.ERROR;
}
return actionInvocation.invoke();
}

struts2 Async Action

Looking to use Struts2 with Serlvet 3.0 Async support.
My first approach was to just handle to writing to the outputstream in the action and returning null. This however returns with a 404 "resource not available". I am attempting to adapt a Bosh servlet inside of a struts action, using ServletRequestAware, ServletResponseAware interfaces to inject the response.
I am using the struts filter dispatcher. Not entirely sure if this is doable,but would be sure happy if someone else has managed to get async to work within a struts action. Perhaps here is an AsyncResult type or someother magic to make this work.
Make sure the struts filter allows async. Here's what that looks like in the web.xml file:
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<async-supported>true</async-supported>
</filter>
Then from within an Action obtain the HttpServletRequest and HttpServletResponse and use the AsyncContext as you would within a servlet:
public String execute() {
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
final AsyncContext asyncContext = req.startAsync(req, res);
asyncContext.start(new Runnable() {
#Override
public void run() {
try {
// doing some work asynchronously ...
}
finally {
asyncContext.complete();
}
}
});
return Action.SUCCESS;
}

Struts2 interceptor change action

I have added Struts2 interceptor, There I want to change calling action if some logic trigger. Currently I can change redirect JSP file after invoke the action. But I need to change the calling action before invoke the the action. Is there any way to invoke different action?
Thank You.
Your intercept method as per your comments would look something like this:
public String intercept(ActionInvocation actionInvocation) throws Exception {
final ActionContext actionContext = ActionContext.getContext();
final HttpServletRequest httpServletRequest = (HttpServletRequest) actionContext.get(HTTP_REQUEST);
HttpSession httpSession = httpServletRequest.getSession(false);
UserObject userObject = session.getAttribute("User"); //Check for user information, this is just a dummy
if(isSpecificUser(userObject)){
return "SpecificAction";
}
return actionInvocation.invoke();
}
SpecificAction should be present in your configuration file.

Problem using HttpServletRequest authenticate() within JSF 2.0 preRenderView listener

I'm trying to use the authenticate() in a preRenderView listener method, in order to trigger authentication conditionally, depending on view parameters in the page. I tried adding a simple method:
#Named
#RequestScoped
public class PermissionBean implements java.io.Serializable {
public void preRender() {
System.out.println("IN PRERENDER");
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
request.authenticate(response);
} catch (Exception e) { // may throw ServletException or IOException
e.printStackTrace();
}
}
The authenticate method itself doesn't throw an exception, it triggers the redirect to Login.xhtml as expected. However, I'm getting in my server log, I get this exception:
enter code here
INFO: IN PRERENDER
FINEST: GET /Login.xhtml previous[3]
INFO: Exception when handling error trying to reset the response.
java.lang.NullPointerException
at com.sun.faces.facelets.tag.jsf.core.DeclarativeSystemEventListener.processEvent(EventHandler.java:126)
at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.processEvent(UIComponent.java:2508)
at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2129)
at com.sun.faces.application.ApplicationImpl.invokeComponentListenersFor(ApplicationImpl.java:2077)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:286)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:244)
at javax.faces.application.ApplicationWrapper.publishEvent(ApplicationWrapper.java:670)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
So my request is not redirected to Login.xhtml.
My question is - is this something that should work within a JSF managed bean, or is it only legal outside of JSF request lifecycle? I tried calling authenticate() from a WebFilter, and it works as exptected.
Thanks,
Ellen
You need to tell JSF to not render the response which it was initially asked to do, whenever the request has been redirected. You can do that by checking if HttpServletRequest#authenticate() returns false and then invoke FacesContext#responseComplete() accordingly.
if (!request.authenticate(response)) {
FacesContext.getCurrentInstance().responseComplete();
}

How to know if HTTP request is GET or POST in Struts 2 action?

Is there a way to know in Struts2 action's method if this is GET or POST request?
Your action should implent org.apache.struts2.interceptor.ServletRequestAware, so your action class should have something like
private HttpServletRequest httpRequest;
// ...
public void setServletRequest(HttpServletRequest request) {
this.httpRequest = request;
}
Then just do:
String method = httpRequest.getMethod() ;
You can use HTTPServletRequest.getMethod() to find out that and handle accordingly in action.
HTTPServletRequest.getMethod()
If you don't want to implement ServletRequestAware just for this, you can get the method with 1 line:
String method = ServletActionContext.getRequest().getMethod();

Resources