Table of Contents
Servlets are programs that run on Web server (or Application server, which is usually called servelt container) and act as a middle layer between the web browser and database (or other application).
Incoming (request) | Servlet | Outgoing (response) |
Data from HTML forms, applets and custom HTTP clients | Processes data and if required makes certain database requests etc. | Response in form of HTML pages or explicit documents (Excel, XML, image formats etc. |
Servlets are created using:
- javax.servlet
- javax.servlet.http
javax.servlet.http.HttpServlet is the abstract class used for HTTP requests. Servlets are not part of Java SE. They are compiled like ordinary Java classes.
Servlet life cycle is the following:
- init() – initializing
- service() – processing client’s request
- destroy() – servlet termination
- GC (Garbage collector) removes the servlet
init()
This method is called only once at servlet creation. Here it may be important to mention that servlets may be created at to moments:
- at server start or
- at first time a clients accesses an URL that is assigned to some servlet
init() creates data that stays with the servlet for its whole life.
service()
When user invokes a servlet a single instance of that servlet is created and for each further request a new thread is created. In that thread, service() is called. It checks for HTTP request and calls:
- doGet() – the default solution (for requests without METHOD specified)
- doPost()
- doPut()
- doDelete()
- etc.
So basically we don’t deal with this method but usually override the required method from this list.
destroy()
This method the same way as init() is called only once but at the end on life of the servlet. It does the cleanup (DB connection close, cookies lists writing etc.)
Servlet Deployment
For example in Tomcat we have the following requirements for deployment:
- <Tomcat_install_dir>/webapps/ROOT – locaiton of servlet application
- <Tomcat_install_dir>/webapps/ROOT/WEB-INF/ – location of web.xml
- <Tomcat_install_dir>/webapps/ROOT/WEB-INF/classes – location of class files
File web.xml (a deployment descriptor) is used for mapping URLs to servlets.
Sample web.xml content:
<servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping>
So <servlet> is used for defining the a name for certain servlet class and the <servlet-mapping> tag is used for linking that name to some URL.
Form data
Data from forms is passed to servlet in 2 ways (methods):
- GET – has a limitation in size (1024 characters) and exposes potentially sensitive information as everything is displayed in URL
- POST – is the preferred way of passing info from forms
For getting fields values there are 3 methods:
- getParameter() – gets the value for certain parameter
- getParameterValues() – all values of a parameter that may have more then 1 value (ex. checkbox, dropdown selects)
- getParameterNames() – a Enumeration of all parameters of current request
Web page structure
- HTTP status code line or the request line – request’s request line looks like: GET /blahblah/foo.jsp?param=paramvalue HTTP/1.1; whilst response’s HTTP status line looks like: HTTP/1.1 200 OK
- Headers – may be zero or more, each in separate line
- Blank line
- Body – may be blank
HTTP status codes
We SET these. Most interesting one may be the 302 code that has to go along with a Locaiton header – this one indicates the URL of the new document.
Headers
While using servlets and web pages in general we have to deal with 2 types of headers:
- Request headers – these we GET
- Response headers – these we SET
In request headers info about media type (Accept – ex. image/jpeg, image/png etc.) may be found along with much other info like charset (Accept-Charset) or browser info (User-Agent).
Filters
Are some classes (that implement javax.servlet.Filter) used either between clients request and backend or server response and client. Filters are deployed in web.xml and mapped to:
- URL patterns or
- servlet names
Filters execute in the order they are declared in web.xml. Note that <filter-mapping> may contain a <servlet-name> – and that is the name of the servlet that if called, causes this filter to execute(http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/web_xml.html#1039330). They are started at the servlet container startup.
Filters have three methods declared in their interface:
- doFilter() – request passes this method as it goes from client to a servlet. doFilter has a parameter called chain, this parameter is of type FilterChain – it is created by the servlet container for all the required filters attached to some resource to be appliend. So at the end of the doFilter() method you have to call chain.doFilter(request, response). This either calls the next filter in the chain or if this is the last filter in the chain the requested resource will be called.
- init() – web container indicates to the filter that it was initialized
- destroy() – web container indicates to the filter that it was stopped
Exception handling
In web.xml we can specify certain servlet to deal with any of the 2 types of situations(for both of them we use the <error-page> tag inside web.xml):
- Exception handling – <error-page> will contain a <exception-type> tag with the name of the exception to be handled and a <location> tag with the name of the servlet to be called for this exception
- HTTP status codes reaction – the same tag <error-page> will contain a <error-code> tag with the number of the HTTP status code (ex. 404) and a <location> tag with the name of the servlet to be called in case of that code
Cookies
Cookies are used for storing different info associated with a certain resource on users computer. Their type is javax.servlet.http.Cookie. Cookies are set in a Http header (Set-Cookie header). Info of the cookie is stored as a key-value pair along with some additional parameters. These parameters are:
- expires – sets a expiry timestamp for this certain cookie
- path – path from domain that this cookie must be applied to
- domain – the domain for which the cookie will be used
There are 2 main players in these elements usage:
- Server scripts – sends cookies to the browser or retrieves them from browser
- Browser – receives cookies from scripts and stores them on computer or retrieves them from computer and sends to the server.
In a servlet cookies are retrieved using the request.getCookies() method, which returns an array of cookies.
Adding cookie to response using Cookie[] response.addCookie(Cookie cookie). Before that you have to initialize one with an ordinary constructor like:
Cookie cookie = new Cookie("key", "value"); cookie.setMaxAge(60*60*24); // 24 hours response.addCookie(cookie);
Reading cookies involves calling request.getCookies() and then for each of the cookie from the array you have to getName() or getValue().
Deleting cookies involves the following three steps:
- storing an existing Cookie in a Cookie object
- setting its age to zero using setMaxAge()
- add that Cookie object to response
Sessions
HTTP is made such a way that from one request to the next it forgets everything. So to bind more requests in one session we may use the request.getSession() method. It returns a HttpSession object. This session is persistent for a set time period (set using setMaxInactiveInterval()). We can add attributes using session.setAttribute(String name, Object value) to the session. Also we can removeAttribute() from session.
When it is not required any more we can invalidate() it.