Java Reference
In-Depth Information
Servlets primarily receive HTML GET and POST requests that originate from
browser forms. GET requests pass their parameters on the command line, for ex-
ample, http://www.mywebsite.com/servlet/Start?parm1=1&parm2=2. POST requests
pass their parameters in a data stream. In either case, the parameters are passed as
name-value pairs and are encoded.
To create a servlet, you extend HttpServlet and override the service() or
the doGet()/doPut() methods. You will need to import javax.servlet and
javax.servlet.http packages to have this compile. These packages are found in the
JEE SDK. The following is a simple servlet:
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>" + "Welcome Page" + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Welcome Page </h1><hr>“);
out.println("Welcome to the web site");
out.println("</body>");
out.println("</html>");
}
}
This servlet is very simple. It sets the content type in the response header so that
the browser knows what type of data (that is, the MIME type) will follow. It then
gets the PrintWriter associated with the HttpResponse object and uses the writer to
write the HTML to the browser. The Web server is ultimately responsible for de-
livering the stream of HTML to the browser.
The preceding code would work fine if your servlet received only GET requests.
The doGet() method would not be called for a POST request. You would need to
override doPost() to receive the POST request.
Search WWH ::




Custom Search