Java Platform, Enterprise Edition/Java EE Tutorial/An Introduction to Servlet
A Servlet is a Java class that runs in the Server machine on an HTTP request from client and creates an html as response to the client. Servlets are stored in a Servlet Container in the Web Server and are mapped to URLs, for which the servlet constructs response.
HTTP Requests
[edit | edit source]GET, HEAD, POST, PUT, DELETE, OPTIONS and TRACE are the request methods defined by HTTP 1.1 [1]. Among these methods GET and POST are the most common. When a client tries to access a URL, he/she is actually sending a GET request to the server while a POST request is used to submit an HTML form.
Requirements for a Servlet
[edit | edit source]- A Servlet responds to HTTP requests (like GET,POST,etc.). In order to respond to any of these requests a servlet class has to extend HttpServlet class and contain their corresponding metod which overrides the original method in the HttpServlet class. For example to respond to a GET request from the client, the source code of the servlet should have the following structure.
public class ServletName extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
.
.
.
.
}
}
In the Servlet, instructions can be written to construct or write the html file to be send. It is explained in next chapter.
- Compile the Servlet source file and place the class file(servlet) in the Servlet Container. Location of the Servlet container is corresponding the Server. For example in Apache Tomcat, the Servlet should be placed in "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ApplicationName\WEB-INF\classes\" (Assuming that "C:\Program Files\Apache Software Foundation\Tomcat 5.5" is the installed directory).
- Set the classpath to the Servlet container.
- Create(or update) the Deployment Descriptor. Deployment descriptor is an xml file with name "web.xml" which should be placed along with the classes folder in the folder, "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ApplicationName\WEB-INF\". How to set servlet properties in the web.xml is detailed in the next chapter.
In the next chapter, we will create and deploy a simple "Helloworld" servlet.
Previous: | First Applet | Up: | Java Platform, Enterprise Edition/Java EE Tutorial | Next: | First Servlet |
---|