The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client.
The servlet example can be created by three ways:
1) By implementing Servlet interface,
2) By inheriting GenericServlet class, (or)
3) By inheriting HttpServlet class
NOTE: The mostly used approach is by extending HttpServlet because it provides http request
HelloWorld.java// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("" + message + "
");
}
}
Note: HttpServlet contains all the life cycle methods of Servlet and the service() method is writen in the following two methods, they are
public void doGet (HttpServletRequest, HttpServletResponse) throws ServletException, IOException
public void doPost (HttpServletRequest, HttpServletResponse) throws ServletException, IOException
To compile the servlet program we have to set a CLASSPATH
..\tomcat\lib\servlet-api.jar
Now compile the HelloWorld.java using following command
javac HelloWorld.java
If the compilation is successfull then HelloWorld.class file will be generated. Copy *.class file into document root/WEB-INF/classes folder
1. Whenever client makes a request to a servlet that request is received by server and server goes to a predefined file called web.xml for the details about a servlet.
2. web.xml file always gives the details of the servlets which are available in the server.
3. If the requested servlet is available in web.xml then server will go to the servlet, executes the servlet and gives response back to client.
4. If the server is not able to find the requested servlet by the client then server generates an error (resource not found).
demo
HelloWorld
demo
/servletdemo
Open broser and write http://hostname:portno/contextroot/url-pattern. For example:
http://localhost:8080/studyglance/servletdemo