Generate Web View using Servlet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Generate Web View using Servlet

Share This

Previously, it has been shown that Servlets have a three-part life cycle: initialization, service, and destruction. An HttpServlet object shares this life cycle but makes a few modifications to the HTTP protocol. 


The HttpServlet object's implementation of the service() method, which is called during each service request, calls one of seven different helper methods. These seven methods correspond directly to the seven HTTP methods and are named as follows: doGet(), doPost(), doPut(), doHead(), doOptions(), doDelete(), and doTrace()


The appropriate helper method is invoked to match the type of method on a given HTTP request. The HttpServlet life cycle can be illustrated as shown in the following figure.

While all seven methods are shown, remember that normally only one of them is called on a given request. More than one might be called if a developer overrides the methods and has them call each other. The initialization and destruction stages of the Servlet life cycle are the same as described before.


Coding an HttpServlet is straightforward. The javax.servlet.http.HttpServlet class takes care of handling the redundant parts of an HTTP request and response, and requires a developer only to override methods that need to be customized. 


Manipulation of a given request and response is done through two objects, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse. Both of these objects are passed as parameters when invoking the HTTP service methods.

Source Code of HomePageServ.java
package com.t4b.test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/HomePageServ") public class HomePageServ extends HttpServlet { private static final long serialVersionUID = 1L; public HomePageServ() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Home Page!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("<h2>Welcome!</h2>"); out.println("</body>"); out.println("</html>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.