Sending a Normal Response
Let’s begin our discussion of servlet responses with another
look at the first servlet in this book, the
HelloWorld
servlet,
shown in Example 5.1. We hope it looks a lot simpler
to you now than it did back in Chapter 2.
Example 5-1. Hello again
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out.println("<BODY>"); out.println("<BIG>Hello World</BIG>"); out.println("</BODY></HTML>"); } }
This servlet uses two methods and a class that have been only briefly
mentioned before. The
setContentType()
method of ServletResponse
sets the content type of
the response to be the specified type:
public void ServletResponse.setContentType(String type)
In an HTTP servlet, this method sets the
Content-Type
HTTP header.
The getWriter()
method returns a PrintWriter
for writing
character-based response data:
public PrintWriter ServletResponse.getWriter() throws IOException
The writer encodes the characters according to whatever charset is given in the content type. If no charset is specified, as is generally the case, the writer uses the ISO-8859-1 (Latin-1) encoding appropriate for Western European languages. Charsets are covered in depth in Chapter ...
Get Java Servlet Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.