Saturday, January 23, 2016

Servlets and JSP-1

          I am posting some bullet points on Servlets and JSP's . You can use them to brush up your J2EE basics.

Servlets and JSP:

1.  TCP is responsible for making sure that a file sent from one network node to another ends up as a complete file at the destination, even though the file is split into chunks when it’s sent.
2.  IP is the underlying protocol that moves/routes the chunks (packets) from one host to another on their way to the destination .
3.  HTTP, then, is another network protocol that has Web-specific features, but it depends on TCP/IP to get the complete request and response from one place to another.

HTTP conversation is a simple Request/Response sequence

 Request :
   HTTP Method (Header of each method can contain data such as which browser) , post request has a Request body
   Content Type
Why POST than GET

 1. Get the amount of data send is limited. - Long search words
 2. The values are exposed in url - Better not send passwords
 3. GET can be bookmarked however POST cannot be .

Servlet extend HTTPServlet and has doGet and doPost methods.


A special directory exists within the application hierarchy named  WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The  WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

Servlets are not thread safe.  It can be made thread safe by synchronizing service method

A ServletConfig object

One ServletConfig object per servlet.
Use it to pass deploy-time information to the servlet (a database or enterprise bean lookup name, for example) that you don’t want to hard-code into the servlet (servlet init parameters).

Use it to access the ServletContext.

Parameters are configured in the Deployment Descriptor.

A ServletContext

One ServletContext per web app. (They should have named it AppContext.)
Use it to access web app parameters (also configured in the Deployment Descriptor).
Use it as a kind of application bulletin-board, where you can put up messages (called attributes) that other parts of the application can access (way more on this in the next chapter).
Use it to get server info, including the name and version of the Container, and the version of the API that’s supported.

Q: Why would I ever want to get an InputStream from the request?
A: With a GET request, there’s nothing but the request header info. In other words, there’s no body to care about. BUT... with an HTTP POST, there’s body info. Most of the time, all you care about from the body is sucking out the parameter values (for example, “color=dark”) using request.getParameter(), but those values might be large. It is also possible to create a servlet that handles a computer-driven request in which the body of the request holds textual or binary content to be processed. In this case you can use the getReader or getInputStream methods. These streams will only contain the body of the HTTP request and not the headers.


The Container initializes a servlet by loading the class, invoking the servlet’s no-arg constructor, and calling the servlet’s init() method.
The init() method (which the developer can override) is called only once in a servlet’s life, and always before the servlet can service any client requests.
The init() method gives the servlet access to the ServletConfig and ServletContext objects, which the servlet needs to get information about the servlet configuration and the web app.
The Container ends a servlet’s life by calling its destroy() method.
Most of a servlet’s life is spent running a service() method for a client request.
Every request to a servlet runs in a separate thread! There is only one instance of any particular servlet class.
Your servlet will almost always extend javax.servlet.http. HttpServlet, from which it inherits an implementation of the service() method that takes an HttpServletRequest and an HttpServletResponse.
HttpServlet extends javax.servlet.GenericServlet—an abstract class that implements most of the basic servlet methods.
GenericServlet implements the Servlet interface.
Servlet classes (except those related to JSPs) are in one of two packages: javax.servlet or javax.servlet.http.
You can override the init() method, and you must override at least one service method (doGet(), doPost(), etc.).

The HttpServlet’s doGet() and doPost() methods take an HttpServletRequest and an HttpServletResponse.
The service() method determines whether doGet() or doPost() runs based on the HTTP Method (GET, POST, etc.) of the HTTP request.
POST requests have a body; GET requests do not, although GET requests can have request parameters appended to the request URL (sometimes called “the query string”).
GET requests are inherently (according to the HTTP spec) idempotent. They should be able to run multiple times without causing any side effects on the server. GET requests shouldn’t change anything on the server. But you could write a bad, non-idempotent doGet() method.
POST is inherently not idempotent, so it’s up to you to design and code your app in such a way that if the client sends a request twice by mistake, you can handle it.
If an HTML form does not explicitly say “method=POST”, the request is sent as a GET, not a POST. If you do not have a doGet() in your servlet, the request will fail.
You can get parameters from the request with the getParameter(“paramname”) method. The return value is always a String.
If you have multiple parameter values for a given parameter name, use the getParameterValues(“paramname”) method that returns a String array.
You can get other things from the request object including headers, cookies, a session, the query string, and an input stream.

You use the Response to send data back to the client.
The most common methods you’ll call on the response object (HttpServletResponse) are setContentType() and getWriter().
Be careful—many developers assume the method is getPrintWriter(), but it’s getWriter().
The getWriter() method lets you do character I/O to write HTML (or something else) to the stream.
You can also use the response to set headers, send errors, and add cookies.
In the real world, you’ll probably use a JSP to send most HTML responses, but you may still use a response stream to send binary data (like a JAR file, perhaps) to the client.
The method you call on your response for getting a binary stream is getOutputStream().
The setContentType() method tells the browser how to handle the data coming in with the response. Typical content types are “text/html”, “application/pdf”, and “image/jpeg”.
You don’t have to memorize content types (also known as MIME types).
You can set response headers using addHeader() or setHeader(). The difference depends on whether the header is already part of the response. If it is, setHeader() will replace the value, but addHeader will add an additional value to the existing response. If the header is not already part of the response, then setHeader() and addHeader() behave in exactly the same way.
If you don’t want to respond to a request, you can redirect the request to a different URL. The browser takes care of sending the new request to the URL you provide.
To redirect a request, call sendRedirect(aStringURL) on the response.
You cannot call sendRedirect() after the response is committed! In other words, if you’ve already written something to the stream, it’s too late to do a redirect.
A request redirect is different from a request dispatch. A request dispatch (covered more in another chapter) happens on the server, while a redirect happens on the client. A request dispatch hands the request to another component on the server, usually within the same web app. A request redirect simply tells the browser to go a different URL.

Redirect vs RequestDispatcher

Redirect - Client does the work

RequestDispatcher - Server does the work
RequestDispatcher view = req.getRequestDispatcher("New.jsp");

You cannot get initParameters in constructor
when you override init you override no-args init.  servlet has two versions of init - init() and init(ServletConfig). Second one calls the first. Hence while overriding init(), You will have ServletConfig.

If we want a parameter through out the application , We use Context-params

-for particular servlet
  <param-name> firstparam </param-name>
  <param-value> firstValue</param-value>


Across application


outside servlet tag inside web-app>


If the app is distributed, there’s one ServletContext per JVM!

Usecase :
  ServletContext parameters are Strings , But you need to create a DataSource Reference object to be accessible to all the Servlet .  This cannot be done normally. What we need here is a Listener which listens to the Context initialization event.  Which will run on context initialization which happens only once.
  two methods - public void contextInitiallized(ServletContextEvent) ->ServletContextEvent.getServletContext will give you ServletContext.
Having got ServletContext you can set Attribute in that.

Friday, September 25, 2015

Remembering JSP Actions

JSP  mainly has 4 Types of actions

   Jsp usebean is used to associate a variable with an instance of a class . An example  is :

 <jsp:useBean id="today" class="java.util.Date"/>

setProperty and getProperty

    These actions are used to set or get property values from the variables defined using useBean  an Example :

 <jsp:useBean id="employee" class="testpackage.Employee"/>
<jsp:setProperty name="employee" property="firstName" value="someName"/>
First Name: <jsp:getProperty name="employee" property="firstName"/>

JSP Include and Forward 

    Jsp Include is used to include another resource dynamically . This should be a JSP page .
Difference between a JSP include and an Include directive is that , the JSP include adds the resource to the page in runtime while the other does in the time of translation .

  JSP forward forwards the current page to a different resource

Remembering JSP's

Lets look at some old JSP  terminologies

  JSP's are servlets
     All Jsps get translated to servlets during runtime. The servlet class name is normally decided by the servlet container . All these servlet classes extends implements jspPage interface .  When requested for the first time ,webserver compiles JSP page to the class and on subsequent requests it doesn't re compiles unless changes has been observed in the JSP Page .

JSPInit() and JSPDestroy()
          You can override JSPInit and JSPDestroy() methods in the JSP declaration tags. Doing this allows you the handle to the init() and destroy() functions of the jsp servlet.

JSP mappings in web.xml

         JSP's are mapped in web.xml's  to a particular url pattern . Init Parameter is also defined here.

Implicit Objects
      There are set of implicit objects in JSP pages which you can use without declaring it explicitly .
They are :

  request - servletRequest
  response - servletResponse
  out - PrintWriter (JspWriter)
  session - HTTPSession
  application -  ServletContext
  config - ServletConfig
  pageContext - pageContext
  page - JspPage
  exception - Throwable

Scopes of Variables in JSP 
           In Jsp a variable can be stored in 4 Scopes page, request , session and applicationScope
page - only for the page, request - ServletRequest , session - HttpSession  , application - ServletContext . The setAttribute method in PageContext has the following signature:

public abstract void setAttribute(java.lang.String name,
        java.lang.Object value, int scope)
         The value of scope can be one of the following static final ints in PageContext: PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE.

JSP Include Directive
  <%@include file ="url" />   is known as include directive in JSP pages. These are used to keep the code separated and have a modular architecture . When we do a jsp page include, it replaces the directive with the contents of the url page.

Scriptlets , Expressions and Directives

  The scriplets are "<%"  which shows beginning of the java code in JSP page .
   "<%=" are Expressions which calls a method and returns the value to output stream of JSP
  "<%! "  are directives which mark starting of a method definitions in the JSP page

Wednesday, August 5, 2015

Pending Interuppts in Java

     Interupts can be kept pending till the first Sleep call . A thread can continue to execute even if it is interrupted and throws an InterupttedException on the call of sleep method :

 Have a look at a sample code:

   Public class TestInteruppt{
     public static void main(String args[]){
}catch(InterruptedException E){
 System.out.println(" This is a Pending Interupt");


Difference between Thread.interrupted() and isInterrupted

       Thread.interrupted() is a final static method which is defined in the base thread class  and isInteruptted is a non static method in the thread class. Both returns the interrupt status of the thread.  One is called on the object of the thread to get the status since the interrupted() method is static this is called by Thread.interrupted().
      Thread.interrupted() returns true if the thread has interrupt flag set and resets the interrupt flag. while isInterrupted() method is a check for the flag and doesnt resets the flag

Thursday, July 23, 2015

Validating an XML with DTD in Java

      In this example i will show you how to validate an incoming xml . To validate an XML you have two options . One is to use XSD and second one is to use DTD's . I will explain you about XSD and why its is better compared to DTD's in a different post . In this post i will try to explain you about DTD's  and how will we validate a XML document.

 DTD's are non-xml documents which defines characteristics of an incoming xml . DTD's can be a separate document or can be included in the same XML . Lets look at a sample DTD defined XML

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE students [
   <!ELEMENT students (student+)><!-- any Number of students -->
   <!ELEMENT student (studentid, name)><!-- student can have only two elements -->
   <!ATTLIST student department CDATA #REQUIRED> <!-- department is required -->
   <!ELEMENT studentid (#PCDATA)><!-- studentId is parsable String -->
   <!ELEMENT name (#PCDATA)>
  <student department="computers">
  <student> <!--  Gives a parser Exception as department is required. -->

   The DOCTYPE element is the DTD , It defines how the XML is expected to be . Lets look closely at what  this DTD means

1. The root element is students.
2. Students tag can contain one or many elements of student type. (+ indicates one or more , * indicates zero or more)
3. Student type contains two elements studentid and name.
4. Department is Required.
5. StudentId and Name should be a parsable Data .  PCDATA means parsed character data

More details on writing DTD's is found here .

Lets look how we write a java code to validate the XML . While doing a domBuilder parse , we have to set the factory to be validating true. In case you have to handle the validation errors with custom logic then you have to use the setErrorHandler method (of builder)  and pass a custom ErrorHandler Class

public class DTDValidator {

 public static void main(String[] args) throws SAXException,ParserConfigurationException,IOException {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse("src\\com\\learning\\xml\\student.xml");
        //builder.setErrorHandler(<Custom Implementation Of Error Handler );
  System.out.println("Successfully Parsed");

Tuesday, July 21, 2015


   I will take this blog post to point you what all are the key differences between an XML and HTML  and what all are the rules driving both of them .

1. XML is case sensitive while HTML is not.
    <BR> and <br> are two different tags for xml but html consider both as one.

2. Close tags are not mandatory for HTML .
    HTML parser is not so strict and it will not complain you if you have missed a closing tag. It understands from the context. However XML is strict with respect to closing tags.

3. An Attribute without a value is valid for HTML  but not for an XML
   <table name="table1" visible>  is a valid HTML but not a valid XML . To be a valid xml this should be  <table name="table1" visible="true">

4. Attribute values should be given inside a "double quote" for XML, However HTML doesnt stick to this rule <table name="table1" visible=true> is a valid HTML.

Hope it helps . Happy coding :)