Friday, December 19, 2014

Servlets and JSP

Here is a quick overview on getting started with Java Web Development.

J2EE Development

IDE

Preferably an IDE like Eclipse or NetBeans to organize your code.  I use Eclipse.  You can find the latest build for developing Java EE applications here.  Luna is currently the most recent release.

https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunasr1

Server

You'll also need a Server to host your web application.  You can use Apache's Tomcat, Oracle's Glassfish, IBM's JBoss and other server app's suited for Java Dev.    Link to download Tomcat is below:

http://tomcat.apache.org/

Servlets

These are special applications that are hosted on your web server that enhance its functionality.   They are part of the J2EE suite of technologies used to make web applications.  When a client from a browser sends a request, the server reads the client request, invokes the right servlet to handle the request and then returns the response to the client.

The servlet may also forward the request to another servlet to handle the request and that in turn may return the response.

Why did we develop Servlets?

As the paradigm for layers and tiers developed in the software world, there was a large motivation to separate responsibility.  In an typical Model View Controller architecture, our View would be written in JSP or HTML, our Controller would be written using Servlets and our Model would be represented by a Enterprise Java Bean.  Functioning as the Controller, Servlets provided a way to process requests from the view, fetch data from the model/the database and then provide the results back to the view.

Java Support for Servlet

1.javax.servlet
2.javax.servlet.http

These are the two major packages that provide libraries for implementing Servlets and its related life cycle.  Your Servlet class is nothing but a java class that implements GenericServlet or HttpServlet class.  These classes provide the lifecycle methods for the servlet.

Generic Servlet is a protocol independent implementation of the Servlet interface.  HttpServlet is a protocol dependent implementation namely that of the Http protocol and serves http requests like a get or post.


Web.XML or Deployment Descriptor

This is the configuration file present in the WEB-INF folder of your application that enables the container to provides initialization parameters to the context, servlets and jsp files.  It can also be used to get the list of welcome files, get filters, listeners and so on.  Annotations are an alternative way to do this and reduce clutter in the web.xml available from Servlet version 3.0.

GET versus POST method

The HTTP Get request is usually sent by the browser to query or get data from the database.  These will usually correspond to database reads.  The HTTP Post requests are those that contain data and typical update/write something in the database.

The HTTP Get request contains the data it needs as a query string which is part of the request URL.  For this reason, it isn't suitable to transmit secure information like passwords.  In the HTTP Post request, the data is not submitted as part of the url but as part of the request body.  This is the reason its more suitable for secure data.

Another difference is that the GET request places a limit on the amount of data to be sent (the number of characters on the url string is limited), the POST method doesn't place a limit on the amount of data that can be sent.

GET is also non-idempotent - repeated get requests will give you the same result.  Post is idempotent - multiple requests will not give you the same result - eg first time you register on a website, your account is created.  Second time the same action will not happen.

So why ever use GET?  

Usually when you refresh a page with a POST method, the browser will ask you if you surely want to do that since that action may cause some action to be repeated.  This is the browser's way of making sure you don't perform any repeated updates.  This doesn't happen with the GET method.

Get is the default method that invoked if nothing is specified.


Understanding Servlet Lifecycle

You have the following methods:

1. init()
2. service()
3. destroy()

Init and destroy methods are called only once per servlet.  The service method is called various times for each servlet and every new request is handled by a new thread.

Init can be used to do all action common to all servlets like making database connections and so on.

The web server creates a new request and response object for every request that comes in and passes it to the server.  Its up to the server to keep track if subsequent requests come from the same browser.

Servlet API


ServletContext
  • This is provided by the container is common to all Servlets in your application.
  • It is created by the container when the application is started and destroyed only when the application is destroyed.  
  • They can supply initialization parameters that are common to a group of servlets in the application.
  • This provides access to application level attributes specified using <context-param> in web.xml file. 
  • Accessed by using the getServletContext() method and getAttribute() and setAttribute() methods allow us to store attributes in the context to be accessed by other servlets.
Servlet Config
  • This is used to specify some initial configuration for each servlet.
  • The servlet config is part of the ServletContext
  • The initialization parameters supplied as part of class annotations or in the web.xml file are available as part of the Servlet Config.  These are specific to a particular servlet.
  • Accessed by using getServletConfig() method.
  • There's no way to set/get attributes from the servlet configuration.
Init Parameters

This is data that is passed to the servlet when it is initialized.  This is different from data passed to the servlet from the doGet and POST method which come directly from the client.  The init parameters often help to set default values.

Parameters can be specified as part of Annotations in the servlet class file or as part of the web.xml.

Annotations versus Web.xml
  • When specified as part of web.xml, we can change the value of init parameters without needing to recompile the servlet class.  We only need to restart the server.  Annotation will require you to recompile the class and redeploy on the server.
  • Annotation are simple and are maintained per class level.  They are easier to maintain for application with large number of servlets where entering them in web.xml can be error prone.
  • IDEs like Eclipse provides support to write annotations and pre insert in the class during creation
Attributes Scope

These are data that can be stored that provides data about the request.

You can have attributes in the request, session and context scope.
  1. Request Attributes - Request is specific only to one particular request.  Another request from the same browser will not retain request variable. 
  2. Session Attributes - Session attributes are stored across different requests from the same browser session.  If the user switches his browser, then the session isn't retained. 
  3. Context Attributes - Context or application scope attributes are ones which are available across servlets and remain active till the application is alive.

1 comment:

  1. So why ever use GET? This section can be improved a bit more. The main purpose of GET in REST is to retrieve something from the server and render it (in the browser scenario)

    ReplyDelete