6.3. Returning the HTTP Response
Problem
You want to create a response in the Action and
send that response to the client instead of forwarding to another
action or JSP page.
Solution
Use the standard methods provided by the
HttpServletResponse object to write the response.
Then return null instead of an
ActionForward from the execute() method of the Action. Example 6-2 shows an Action that
creates and returns a simple response.
Example 6-2. Writing the HTTP response in an action
package com.oreilly.strutsckbk.ch06;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class ResponseWriterAction extends Action {
public ActionForward execute( ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
response.setContentType("text/html");
PrintWriter out = response.getWriter( );
out.write("<html><head></head><body>Hello World!</body></html>");
return null;
}
}Discussion
The typical Action returns an
ActionForward from its execute(
) method. The returned ActionForward is evaluated and processed by the Struts request processor. The returned forward specifies the path to a resource, like a JSP page, that generates the actual HTTP response. However, you can generate the response in the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access