12/30/2008

HttpServletResponse

The HttpServletResponse interface extends the ServletResponse interface.

Getting a PrintWriter object for output
PrintWriter getWriter()
javax.servlet.ServletResponse has this method.

Character encording
void setCharacterEncoding(String charset)
    Invoke it before the getWriter.
    Invoke it before the response is committed.
void setContentType(String type)
    Invoke it before the getWriter
    Invoke it before the response is committed.
javax.servlet.ServletResponse has these methods.

Redirect
void sendRedirect(String location)
Specify the relative path. If the relative path starts with "/", it's relative to the container root.
    e.g.    /scwcd/Test
    e.g.    Test
The sendRedirect method returns a response to the client, and then redirects it to "location".
You cannot use request attributes.
If you want to redirect a response to other domain, specify "location" like "http://...".

URL rewriting
String encodeUrl(String url)
String encodeRedirectURL(String url)
URL rewriting is for creating a session for a browser that doesn't support cookies.
These methods are used for "location" for the sendRedirect method.

<Sample>
import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Test extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
        if (req.getParameter("information").equals("")) {
            res.sendRedirect("/scwcd/index.html");
        } else {
            PrintWriter out = res.getWriter();
            out.println("<html><body>");
            out.println(req.getParameter("information"));
            out.println("</body></html>");
        }
    }
}

index.html
...
<form action="/scwcd/Test" method="post">
<input type="text" name="information" size="30" maxlength="15" /><br />
<input type="submit" value="Send"/>
</form>
...

<Result>
What you put will be displayed. If you don't put anything in the form, nothing can be displayed.