Bloom Lab
Pages
Home
Bloom Code Guidelines
Monday, August 3, 2015
Java Servlets
## Servlets A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Another words, servlets extend the capabilities of servers that host applications accessed by means of a request-response programming model. Basically servlets are usually used to implement web applications. Servlets provide *"Here is an HTTP request, write to this HTTP response"* interaction flow. There are various frameworks which operate on top of servlets *(e.g. Struts)*. Java Servlets are part of the Java EE. Servlets run inside a servlet container *(e.g. Tomcat, Jetty web servers)* which handle the networking side (e.g. parsing an HTTP request, connection handling etc). All servlets must implement the `Servlet` interface, which defines lifecycle methods. The `HttpServlet` class provides methods, such as `doGet` and `doPost`, for handling HTTP-specific services.
---- ## Application Life-cycle listener `@WebListener` annotation is used to define a listener in a web application. Your annotated listener classes should implement `ServletContextListener`, which contains two methods `contextInitizlized` & `contextDestroyed`: @WebListener() public class TestServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); String msg = "my listener"; context.setAttribute("listenerMessage", msg); } public void contextDestroyed(ServletContextEvent sce) { } ---- ## Filtering Requests and Responses The filtering API is defined by the `Filter`, `FilterChain`, and `FilterConfig` interfaces in the `javax.servlet` package. You define a filter by implementing the `Filter` interface. `@WebFilter` annotation is used to define a filter in a web application. Classes annotated with the `@WebFilter` annotation must implement the `javax.servlet.Filter` interface. The annotated filter must specify at least one URL pattern by using the `urlPatterns` or value attribute on the annotation. @WebFilter(filterName = "TestFilter", urlPatterns = {"/"}, initParams = {@WebInitParam(name = "mesg", value = "my filter")}) public class TestFilter implements Filter { If you need to pass initialization parameters to the filter, you retrieve them from the `FilterConfig` object passed to init: public void init(FilterConfig filterConfig) throws ServletException { mesg = filterConfig.getInitParameter("mesg"); } `doFilter` is the most important `Filter` interface method which applies request, response, and filter chain objects. So, it can examine request/response headers, modify request/response objects, invoke the next filter in the filters chain or throw an exception to indicate an error in processing. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { req.setAttribute("filterMessage", mesg); chain.doFilter(req, res); } A web container uses filter mappings to decide how to apply filters to web resources. You specify a filter mapping list for a WAR in its deployment descriptor *(web.xml)*. The filters are invoked in the order in which filter mappings appear in the filter mapping list of a WAR. ---- ## Misc ### Invoke other web resources Web components can invoke other web resources. To invoke a resource available on the server that is running a web component, you must first obtain a `RequestDispatcher` object viausing the `getRequestDispatcher("URL")` method. You can get a `RequestDispatcher` object from either a request or the web context. *Note:* that a request can take a relative path, but the web context requires an absolute path. ### Include other web resources It's also possible to include other resources in response via invoking the `include` method of a `RequestDispatcher`: include(request, response); If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then include the result of the execution in the response from the containing servlet. Note: Included web component cannot set headers or call any method like a `setCookie`, that affects the headers of the response. ### Forward to other web resources You might want to have one web component do preliminary processing of a request and have another component generate the response. To transfer control to another web component, you invoke the `forward` method of a `RequestDispatcher`. When a request is forwarded, the request URL is set to the path of the forwarded page. *Note:* If you have already accessed a `ServletOutputStream` or `PrintWriter` object within the servlet, using `forward` will throws an `IllegalStateException`, cause u won't be able to fully forward responsibility for replying to user. ---- ### Accessing the Web Context You can retrieve the web context object *(implements the `ServletContext` interface)* in which web components execute by using the getServletContext method. public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); .... } Through the web context you can access to: * Initialization parameters * Resources associated with the web context * Object-valued attributes * Logging capabilities *The counter's access methods are synchronized to prevent incompatible operations by servlets that are running concurrently.* ### Maintaining the Client Session Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions. It's useful when an application requires that a series of requests from a client be associated with one another. You access a session represented by an `HttpSession` object by calling the `getSession` method of a request object. You can associate object-valued attributes with a session by name. Those are accessible by any web component that belongs to the same web context and is handling a request that is part of the same session Your application can notify web context and session listener objects of servlet lifecycle events. You can also notify when the object is added to or removed from a session via implementing `javax.servlet.http.HttpSessionBindingListener` interface. To notify when a session will be passivated or activated *(when it is moved between virtual machines or saved to and restored from persistent storage)* you have to implement `javax.servlet.http.HttpSessionActivationListener` interface. ### Session timeout Each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed by using a session's `getMaxInactiveInterval` and s`etMaxInactiveInterval` methods. * To ensure that an active session is not timed out, you should periodically access the session by using service methods because this resets the session's time-to-live counter. * When a particular client interaction is finished, you use the session's `invalidate` method to invalidate a session on the server side and remove any session data. ### User Session To associate a session with a user u've to pass an user identifier between client-server. User ID can be stored on the client as cookie or the web component can include the identifier in every URL that is returned to the client. *Note:* In anyway you have to support second approach if the client has a disabled cookies. In this case you have to rewrite all URLs by calling response's `encodeURL(URL)` method on all URLs returned by a servlet. ### Clean shutdown To ensure a clean shutdown, your destroy method should not release any shared resources until all the service requests have completed: * One way to do so, is track service requests via including in your servlet class a field that counts the number of service methods that are running. The `service` method should increment the service counter each time the method is entered and should decrement the counter each time the method returns. * Second way to ensure that your `destroy` method do not release any shared resources until all the service requests have completed is to notify long-running methods that it is time to shut down. Here the Oracle example to make a clean shutdown: public void destroy() { /* Check to see whether there are still service methods /* /* running, and if there are, tell them to stop. */ if (numServices()> 0) { setShuttingDown(true); } /* Wait for the service methods to stop. */ while (numServices()> 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } } } *Note:* To shutdown clearly methods that might run for a long time should check the value of the field that notifies them of shutdowns `isShuttingDown()` and should politely interrupt their work, if necessary. ###Upload Files To upload files with Java Servlet `javax.servlet.annotation.MultipartConfig` annotation is used. Servlets that are annotated with `@MultipartConfig` can retrieve the Part components of a given `multipart/form-data` request by calling the `request.getPart(String name)` or `request.getParts()` method. ###Asynchronous Processing Java EE provides support of asynchronous processing for servlets and filters. If a servlet or a filter reaches a potentially blocking operation when processing a request, it can assign the operation to an asynchronous execution context and return the thread associated with the request immediately to the container without generating a response. To enable asynchronous support use the `@WebServlet` annotation parameter `asyncSupported=true`. @see [Asynchronous Processing in Servlets Oracle description](http://docs.oracle.com/javaee/7/tutorial/servlets012.htm) ###Non blocking IO Even if you use asynchronous processing for all the application-specific blocking operations inside your service methods, threads associated with client requests can be momentarily sitting idle because of input/output considerations. @see [Nonblocking I/O Oracle description](http://docs.oracle.com/javaee/7/tutorial/servlets013.htm) ---- ## see Also * [Oracle Tutorials - Types of Web Services](http://docs.oracle.com/javaee/7/tutorial/webservices-intro002.htm) * [Oracle Tutorials - Creating a RESTful Root Resource Class](http://docs.oracle.com/javaee/7/tutorial/jaxrs002.htm#GILIK) * [Jenkov - Java Servlets](http://tutorials.jenkov.com/java-servlets/index.html) * [Docs Oracle - JavaEE 7 API](http://docs.oracle.com/javaee/7/api/) * [Keynote: Exceptions in Action](http://bloomlab.blogspot.com/2015/01/keynote-exceptions-in-action.html) * [Keynote: Understand Java Collections](http://bloomlab.blogspot.com/2015/05/keynote-understand-java-collections.html) * [Keynote: Threads like trains:)](http://bloomlab.blogspot.com/2015/05/keynote-threads-like-trains.html) * [Keynote: Shadowing (Hiding fields)](http://bloomlab.blogspot.com/2015/01/keynote-shadowing-hiding-fields.html) * [Keynote: Initialization Order flow](http://bloomlab.blogspot.com/2014/12/keynote-initialization-order-flow.html)
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment