First Servlet (doGet()) - Let's write your first servelt to handle GET http requests
Let's write our first servlet.
A servlet must extend javax.servlet.http.HttpServlet class. Additoanally it must override method/s specific to the http method/s that it is supposed to handle. If a servlet handls HTTP GET request, it must overide doGet(HttpServletRequest , HttpServletResponse) method. The HttpServlet class is in the servlet-api.jar that can be obtained from the library folder of any web-server that implements servlet specification. In tomcat, servlet-api.jar is present in the $TOMCAT_HOME/lib or $TOMCAT/common/lib folder.
When a client makes an http request, the http web-server (for eg. tomcat) receives it, and calls the appropriate servlet class with an HttpServletRequest object and a HttpServletResponse object. The servlet can use the HttpServletResponse object to construct the http resposne or web-page that it needs to send to the http client. In the example below, the servlet gets a reference to the output stream of the http response using the getWriter() method and adds the content "Hi Friends" to the response.
A servlet must extend javax.servlet.http.HttpServlet class. Additoanally it must override method/s specific to the http method/s that it is supposed to handle. If a servlet handls HTTP GET request, it must overide doGet(HttpServletRequest , HttpServletResponse) method. The HttpServlet class is in the servlet-api.jar that can be obtained from the library folder of any web-server that implements servlet specification. In tomcat, servlet-api.jar is present in the $TOMCAT_HOME/lib or $TOMCAT/common/lib folder.
When a client makes an http request, the http web-server (for eg. tomcat) receives it, and calls the appropriate servlet class with an HttpServletRequest object and a HttpServletResponse object. The servlet can use the HttpServletResponse object to construct the http resposne or web-page that it needs to send to the http client. In the example below, the servlet gets a reference to the output stream of the http response using the getWriter() method and adds the content "Hi Friends" to the response.
package com.techfundaes.servletsBag; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FirstServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pWriter = resp.getWriter(); pWriter.println("Hi Friends"); } }