In most cases we wouldn’t need to access the HttpServletRequestor HttpServletResponse objects directly in a Struts application. However, the framework provides a mean for accessing this request/response couple in case we really have a need, by making our action class implementing the ServletRequestAware or ServletResponseAware interfaces.

 

1. Implementing the ServletRequestAware interface

The following example code shows how an action class implements the ServletRequestAware interface and its method setServletRequest():

public class MyAction extends ActionSupport implements ServletRequestAware {

	private HttpServletRequest request;

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

	public String execute() {
		// access methods of HttpServletRequest object
		String username = request.getParameter("username");
		System.out.println("username = " + username);

		return SUCCESS;
	}

}
When the framework found that an action class implements the ServletRequestAware interface, it will pass an object of type HttpServletRequest into the method setServletRequest() so that we can obtain a reference to invoke servlet request specific methods in the action method.

 

2. Implementing the ServletResponseAware interface

Similarly, the following example code shows the usage of the ServletResponseAware interface:

public class MyAction extends ActionSupport implements ServletResponseAware {
	private HttpServletResponse response;
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public String execute() {
		// access methods of HttpServletResponse object
		// WARNING: this code is for testing only, it is not recommended!
		try {
			PrintWriter writer = response.getWriter();
			writer.println("Something wrong happened");
			writer.flush();	// force to flush the response
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		
		// this return is meaningless because the response has been flushed
		return SUCCESS;
	}
}
As commented in the above code, accessing HttpServletResponse object in Struts 2 action class is not recommended because that would break normal workflow of the framework. Only do that if you have a strong reason.

Now let’s walk through a complete example in which we use the HttpServletRequest object to read values of parameters passed in URL query string, and print them out in the result page.

 

3. Code the Struts Action class



Following is code of the action class (MyAction.java):

package net.codejava.struts;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport implements ServletRequestAware {
	private HttpServletRequest request;
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public String execute() {
		// access parameters from URL query string instead from HTML form:
		String userName = request.getParameter("username");
		String email = request.getParameter("email");
		
		// set values in request scope so that the result page can read
		request.setAttribute("username", userName);
		request.setAttribute("email", email);
		
		return SUCCESS;
	}
}
As the code implies, we read out two parameters username and email from the request. With this way, we can pass the parameters in the URL query string, instead of from an HTML form as usual.

 

4. Code the result page

Here is code of the JSP page (Result.jsp):

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result</title>
</head>
<body>
	<center>
		<h3>User Name: ${username}</h3>
		<h3>Email: ${email}</h3>
	</center>
</body>
</html>
This JSP page simply uses EL expressions to retrieve values of the two parameters which are set by the action class.

 

5. Configuration in struts.xml

And we wires the action class and the JSP page together in struts.xml file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="Struts2ServletExample" extends="struts-default">
		
		<action name="test" class="net.codejava.struts.MyAction">
			<result name="success">/Result.jsp</result>
		</action>

	</package>
</struts>
 

6. Output

The following screenshot shows the output displayed when running the sample application from this URL:

http://localhost:8080/Struts2ServletExample/test?username=Web%20Master&;email=webmaster@codejava.net

Struts2 servlet request example output

 

Related Struts Tutorials:

 

Other Struts Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (Struts2ServletExample.war)Struts2ServletExample.war[Deployable WAR file]3410 kB
Download this file (Struts2ServletExample.zip)Struts2ServletExample.zip[Eclipse project]3414 kB

Add comment

   


Comments 

#2sivakumar2016-01-13 09:29
when i implemented it is as fallows .

public class SubscriptionAction extends AbstractAction implements ServletRequestAware

, it is giving an compile error as fallows
setServletRequest(HttpServletRequest) in SubscriptionAction cannot override setServletRequest(HttpServletRequest) in AbstractAction .
Quote
#1XkMeF2014-07-03 00:29
Nice Material
Quote