Saturday, 28 September 2019

How to access HttpServletRequest and HttpServletResponse within Struts2 action class

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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

No comments:

Post a Comment