How to access HttpServletRequest and HttpServletResponse within Struts2 action class
- Details
- Written by Nam Ha Minh
- Last Updated on 31 July 2019   |   Print Email
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
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
Related Struts Tutorials:
- How to configure Struts framework in web.xml
- Passing parameters from struts.xml to action class
- Reading parameters from web.xml in Struts action class
- Splitting (modularizing) Struts configuration file
Other Struts Tutorials:
- Introduction to Struts 2 framework
- Struts beginner tutorial (Eclipse + Tomcat + XML)
- Struts Beginner Tutorial with Annotations
- Struts beginner tutorial with Convention Plugin (zero-configuration)
- How to handle exceptions in Struts
- Send e-mail with attachments in Struts
- Struts File Upload Tutorial
- Struts - Spring - Hibernate Integration Tutorial
Comments
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 .