Servlet basics


Published on

This article tries to demystify HTTP, "servlet", "web server", "application server", "servlet container" and gives the fundamentals of the Java Servlet API (that comes with the J2EE SDK).

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Servlet basics

  1. 1. HTTP Basics, Web Server, Servlet Container and the Java Servlet APIThis article tries to demystify HTTP, "servlet", "web server", "application server","servlet container" and gives the fundamentals of the Java Servlet API (that comes withthe J2EE SDK). Introduction to HTTPThe ABC of HTTP HTTP (Hyper Text Transfer Protocol) is one of the numerous protocols,which computers use, to talk to each other (just the same way two human beings need acommon language to communicate). When I say talk to, I mean, exchanging data. In theclient-server world, a client is the machine that makes the first call to the server (thinkingof the word "accost", which means to approach and to speak first). A machine can beboth client and server.When a computer initiates a connection to another computer, in HTTP jargon, it is arequest. When the server computer sends data back, it is a response. An HTTP serveraccepts request from any client and always sends a response. Once a response is sent, theserver does not retain information about the request. Neither does it retain anyinformation about the client. That is why HTTP is a stateless protocol.HTTP Requests An HTTP request has three parts: (a) a request line, (b) one or moreheaders and (c) a message. The message is optional. (a) Request Line: A request looks like: GET /science /light.html HTTP/1.1 GET is the name of the method. In HTTP 1.0, other methods are: HEAD and POST. In HTTP 1.1, additional methods available are: PUT, OPTIONS, DELETE, TRACE, CONNECT. The second token of the message, "/science/light.html", is a URI. URI stands for Universal Resource Identifier. URI gives information about the location of the resource to be gotten. The last token is the version of HTTP to be used. The current version is 1.1. GET method is used to retrieve a resource identified in the URI. The POST method, on the other hand, is used to send data to the server. GET can also send data to the server, but is limited to 255 characters, and is in the form of name-value pairs, separated by ampersand. An example of sending data to the server using GET is: GET /science /light.html?user=john&pwd=abcd HTTP/1.1
  2. 2. POST method is used to send HTML FORM values to the server. GET and POST are the common methods used. (b) Headers:Headers contain meta-information. Meta-information means information about information. They include information like: what is the type of data (character, binary etc.), what is the size of data (in Kilobytes). (c) Message: Message body is optional. POST has a body with all the information from the HTML FORM. GET does not have one. If a message body exists, it is preceded by a blank line.HTTP Responses A HTTP Response, the same way, has a (a) response line, (b) one ormore headers, and (c) a message. (a) Response Line: A response line looks like: HTTP/1.0 200 OK As you might have guessed, the first token is the HTTP version. The second token is one of the many predefined status codes, and the last one is an English description of the code. (b) and (c) share the same characteristics as that of as a HTTP Request.Behind buzzwords: Web Server Web Server is a machine that has a HTTPD service running. A web server is the one that handles HTTP requests and generates HTTP responses. Servlet A Servlet is a server-side entity for servicing HTTP requests.Servlet ContainerA Servlet Container is a sub-set of a Web Server. A Servlet Container is a separatemodule; it may run within the web server as a single program (called Standalone, in thiscase), may run as a different program, but part of the same address space (In-Process), orrun in different process-spaces. Tomcat is a very popular standalone servlet container,and can be acquired from ApplicationA web application is an application that is accessible from the web. In that sense, allservers working towards the purpose of running a web application is an applicationserver.Application ServerTomcat is an application server, in that sense, if that is the only server used in an
  3. 3. application. An application may use other servers, like BEA WebLogic or IBMWebSphere. These application servers provide additional services like an EJB Server, aJMS Server, a JNDI Naming Server, etc.The world of Java ServletsSun provides a set of specifications, which dictate how a servlet would communicate witha web server. Tomcat is a servlet container that conforms to those specifications. So,when application developers use the Servlet API, we are happy campers, because Tomcathas implemented the Java interfaces we are going to use. API stands for ApplicationProgramming Interface. It is a set of classes and interfaces for us to use. Servlet API is apart of Suns J2EE SDK, that can be downloaded from APIjavax.servlet.Servlet (interface)This is the numero uno interface of the entire API. Any Servlet class implements thisinterface. The five methods to implement are: init(), service(), destroy(),getServletConfig() and getServletInfo()javax.servlet.GenericServlet (abstract class)Abstract class, implements the java.servlet.Servlet interface, provides implementation ofall methods except the service method.javax.servlet.ServletRequest (interface)This interface abstracts a Request.javax.servlet.ServletResponse (interface)A generic interface for abstracting a response.javax.servlet.http.HttpServlet (abstract class)Extends GenericServlet. Has a new method:protected void service (HttpServletRequest request, HttpServletResponse response)throws ServletException,;javax.servlet.http.HttpServletRequest (interface)This interface extends ServletRequest, and gives HTTP-specific functionality to retrieveinformation about request headers, request parameters, request attributes.javax.servlet.http.HttpServletResponse (interface)Extends ServletResponse. Provides abstraction for a HTTP response. Methods to setheader types, content types and response body exists.
  4. 4. javax.servlet.ServletContext (interface)This is an important interface to understand. It provides a rendezvous for all servlets,JSPs of a web application to share common knowledge. There is one and onlyServletContext for an application. Methods to look for are:java.netURL getResource(String relativePath) getResourceAsStream(String relativePath)javax.servlet.ServletConfig (interface)ServletConfig helps us get the values of initialization parameters as declared in thedeployment descriptor file. A "deployment descriptor" is a XML document, which can beused to declare initial parameters that the application can use at run-time. Thedeployment descriptor is named "web.xml". A snippet of web.xml with servletinitialization parameters:<web-app> <servlet> <servlet-name>HumbleServlet</servlet-name> <servlet-class>com.abcd.HumbleServlet</servlet-class> <init-param> <param-name>jdbcDriverName</param-name> <param-value></param-value> </init-param> <init-param> <param-name>parameterOne</param-name> <param-value>23</param-value> </init-param> </servlet>
  5. 5. .... </web-app>Now it is easy to get the parameter value by calling getInitParameter (StringparamName), which returns a String. Database driver names, classes, urlss are goodcandidates for (interface)Servlet container implements this interface. A representation of a session. The containertakes care of associating the right session for a user.javax.servlet.RequestDispatcher (interface)Interface to pass ServletRequest, ServletResponse objects between servlets. From aservlet, one can use it to forward control to a different servlet, a JSP, a HTML or anyresource using the method:public void forward(ServletRequest request, ServletResponse response)throws ServletException, IOExceptionFor including contents of a different resource, one can use:public void include(ServletRequest request, ServletResponse response)throws ServletException, IOExceptionAccessing a database from a ServletIt is very easy to access a database from a Servlet. If using JDBC, then one can instantiatea driver class and get hold of a ?connection? object. The driver class and connectioninterface is a class provided by Sun in its software development kit (SDK, for short).Both J2SE and J2EE come with their driver classes.Connection to the database can be configured in the deployment descriptor file. Anothertrick would be to get the connection in the init(..) method. This way, the same connectioncan be re-used. Care must be taken to use connection objects, because a connection to adatabase is expensive, and can slow your application down.If you chose to use a persistence layer instead of JDBC, like Object Relational Bridgefrom Apache Software Foundation, or iBatis, then you need not worry about writing codeto access database. Necessary configuration files (XML documents) take care of them.Another thing to keep in mind is servlets are not thread-safe (i.e. multiple threads canaccess the service(...) method.
  6. 6. SummaryWith clearing some of the roadblocks that a "Servlet" newbie might encounter, I amhoping that after reading this article, she or he might be able to go a little deeper into thesubject.Please e-mail if there is anything you want to see here, in the Java Web technologydomain.Prepared by Santosh Dhoundiyal Graphic Era