How to get the HttpServletRequest in Struts 2

In Struts 2 , you can use the following two methods to get the HttpServletRequest object.

1. ServletActionContext

Get the HttpServletRequest object directly from org.apache.struts2.ServletActionContext.


import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

public class LocaleAction{
	//business logic
	public String execute() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return "SUCCESS";
	}
}

2. ServletRequestAware

Make your class implements the org.apache.struts2.interceptor.ServletRequestAware.

When Struts 2 ‘servlet-config‘ interceptor is seeing that an Action class is implemented the ServletRequestAware interface, it will pass a HttpServletRequest reference to the requested Action class via the setServletRequest() method.

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;

public class LocaleAction implements ServletRequestAware{

	HttpServletRequest request;
	
	//business logic
	public String execute() {
		String param = getServletRequest().getParameter("param");
		return "SUCCESS";

	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletRequest getServletRequest() {
		return this.request;
	}
}
Struts 2 documentation is recommended ServletRequestAware instead of ServletActionContext.

Reference

  1. http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletrequest.html
  2. http://struts.apache.org/2.0.6/struts2-core/apidocs/org/apache/struts2/interceptor/ServletRequestAware.html

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
3 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Philippe GioseffiMark KellyFandi akhmad Recent comment authors
newest oldest most voted
Philippe Gioseffi
Guest
Philippe Gioseffi

Actually the documentation instructs us that using ServletRequestAware would make things such as unit testing become more difficult.

http://struts.apache.org/release/2.2.x/struts2-core/apidocs/

Mark Kelly
Guest
Mark Kelly

Why include this method? :

public HttpServletRequest getServletRequest() {
return this.request;
}

Yuu are making the servlet request public unnecessarily

Philippe Gioseffi
Guest
Philippe Gioseffi

The interface makes you implement this method.

Fandi akhmad
Guest
Fandi akhmad

Halo Mkyong,

I use velocity as view in My Struts2, and i list my data from database like this.

...
<a href="./edit.action?id=$emp.id">Edit</a>
...

and generate this URL result :
http://localhost:8080/examplestruts/edit.action?id=2

how i can get request parameter “id” above?

I try to use ServletRequestAware, it success. But, any solution without ServletRequestAware?

Thank you :)