Monday, 7 October 2013

My first servlet application (a)

Creating servlet programming:  using Command Prompt


set up:
Prerequisite:
1. Download any server (Ex: Tomcat, Weblogic,..)
    How to download Tomcat Server
2. Download the jar files and configure
    servlet-api.jar
3. JDK 7
4. Eclipse IDE for Java EE Developers (Juno 4.2)
5. import javax.servlet and javax.servlet.http packages

Table of Content:

1. Create Dynamic Web Project
2. Create Servlet class
3. Deploy the servlet
4. Run and test the servlet

  1. install jdk from http://java.sun.com
  2. install Apache Tomcat from htt://tomcat.apache.org
  3. Eclipse IDE for java EE Developers
  4. Set up the following environment variables
(a) TOMCAT Home: Directory where Tomcat is installed (e.g: c:\Tomcat)
  1. (b) JAVA_Home: Directory where Java is installed (e.g: c:\Java\jdk1.6.0_06)
  2. (c) Add Java_Home \bin directory to CLASSPATH (E.G: c:\java\jdk1.6.0_06\bin)
  3. Put servlet-api.jar in classpath
My first servlet apps

  1. servlet class – business logic
  2. web.xml - configuration file (every web app should follow web.xml file, this is the place where the first server check when the request comes from the client . So when the request comes from the client server goes to this web.xml configuration file checks for that particular request tries to see the match if it finds the match
  1. web.xml - configuration file (every web app should follow web.xml file, this is the place where the server first check when the request comes from the client . So when the request comes from the client server goes to this web.xml configuration file checks for that particular request tries to see the match if it finds the match
  1. web. Jar file :
we have the servlet class , we have the web.xml what you need to do? In order to deploy your application into webserver is : build a jar file out of your classes , html configuration file all those things. So we need to build a jar, including the servlet class and web.xml
  1. Deploy:
  • Once you build a jar, you deploy into the web server.
  1. Execute:
  • Once you deploy the application into the web server
  • application is ready and you can simply go ahead and enter the url and execute your web application 

Now lets have a look in detail

1. first thing is writing your servlet class.

So first servlet application is I'm simply going to print text “hello World” on the screen so when the user enter the url result of that text would be displayed on the web page

  • • I want to make it first application so simple because I would like to do concentrate more on the other things like how do you get all the pieces together and how do you build your jar files , how do you deploy it and I would like to concentrate more on how the code flows between different methods of the class and which order so all those different things about the servlet and web application on the whole so thats the reason I could not put much business logic.
    Just see I have written this code for the servlet and the web.xml file ahead .

    package com.rajservlet.servlets;

    import java.io.IOException;
    import java.io.PrintWriter;
    //these are a part of servlet api jar files, these are the servlet packages.
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class HelloWorldServlet extends HttpServlet // implements javax.servlet.Servlet //no need this interface now
    {
    public HelloWorldServlet()
    {
    super();
    System.out.println(“in HelloWorld Constructor”);
    }
    public void init()
    {
     System.out.println(“In Hello World Init”);
    }
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
      System.out.println(“In Hellow World service()”);
      If(“GET”.equalsIgnoreCase(request.getMethod())
      {
        doGet(request, response);
      }
      else if(“POST”, equalsIgnoreCase(request.getMethod()))
      {
        doPost(request, response);
      }
     }

    Protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
      System.out.println(“in HelloWordl doGet”);
    }
     Response.setContentType(“text/html”);
     PrintWriter out=response.getWriter();
      out.println(“<html>”);
      out.pritnln(“<body>”);
      out.println(“hello World”);
      out.println(“</body>”);
      out.println(“</html>”);
     }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
     System.out.println(“In Hello World doPost()”);
     }
    This is servlet code my servlet is in my package called com.rajservlet.servlet package
  • This is our first “hello world “ servlet,
    ·         My servlet in the package called “com.rajservlet.servlets” package
    ·         We know that in order to write a servlet we need to extend HttpServlet class since we have already imported
    ·         implements javax.servlet.Servlet //no need this interface now: bcoz we know that the HttpServlet extends Generic servlet which inturn implements the Servlet interface .
    ·         So you are Hello World servlet will indirectly be implementing the Servlet interface so we do not write explicitly to implements servlets there
    ·         So once I do the “extends” HttpServlet on the class my class (ie: HelloWorldServlet) has got some features now and those special features are nothing but servlet features or servlet behavior
    ·         I have written all the call back methods in this class during the session init() method, doGet(), doPost(), destroy().
    ·         We have discussed earlier that we don’t need constructor to be declared in a servlet , so practically in real time we don’t put in a constructor  in your servlet because you will not be do anything in the constructor as well. All the initialization code will be in the init() method and jvm will put the default constructor in your servlet class so I simply put “System.out.println() is there in the constructor .
    ·         Next the init() method , this is the place where all your initialization takes place so if you have to perform initialization like getting connection to the database or any other stuff you want to perform in a servlet class , you know that for every request comes in the servlet , the service() method is called which is in turn calles doGet() or doPost() method but the init() method is only calls once when the servlet is loaded so only one time initialization stuff you put in the init() method

    ·         Next service(HttpServletRequest request, HttpServletResponse response) method  it takes the parameters  HttpServletRequest request and HttpServletResponse response throws servlet exception and IOException

    ·         Here one thing please make a note down when do you develop your servlet application in real time  you do not write the service() method as well  in fact you take the default implementation provided by the HttpServlet.
    ·         Again I just put here this service()method so that you will know the flow and when this method is called  and I just tried to emulate (follow) logic which could have been written in the HttpServlet so the HttpServlet class has similar logic but apart from this there will be a lot of other code as of now at this point of time I would …doGet() and doPost() because that is the place I am going to write my business logic so I simply capture the type of method passed by the user so I used request.getMethod()to determine what type of the request the user has sent, if the type is GET, then I call the doGet() method  which passes request and response objects .
    ·         If the type is POST, then I simply call the doPost() method passing the request and response objects.
    ·         So only thing is this service() method is going to do is taking the request, check the type of request, if it is “GET” call the doGet() method , if the type of request is “POST” , call the doPost() method.
    ·         Because it is first call we do not provide any method type it take the GET by default because there  is most specific method provided the default is GET so my doGet() method should be called now so that is the reason I put all the business logic in the doGet() method which again this doGet() method again take the HttpRequest and HttpResponse the parameters and I simply give a print statements here that is “In Hello World in doGet()”
    ·         One thing setContentType() , means setting the content type is to text or html so this is going to tell the client that the type of response I’m sending back to the client is of type html, if you would have been sending pdf document to the client , simply set “application/pdf”. I sent this content type to the response sent back to the client .
    Here I’ m creating PrintWriter object will be displayed on my servlet application.

HelloWorld servlet program

YOu may like the following posts:

Wednesday, 4 September 2013

URL Rewriting

Session Management -URL Rewriting

Sessions-URL Rewriting


  • so for we have seen one of maintaining the session.
  • second way is URL rewriting, so what does it mean
  • client basically can disable cookies so client have the ability to disable cookies on their computer. So client can say I do not trust anyone and I do not want to accept any cookies from any of the websites
  • So it disables cookies, so server will not able to send cookie to the client even though the server is sending a cookie that cookie will not store on the client machine. So how can session can maintained in that scenario. Answer to that is URL Retwriting.
  • In the case of URL Rewriting what happens is "JSESSIONID" which earlier cookie was sent in a cookie, now will be appended to the URL which is sent to the client
  • so whatever URL the server sent back to the client along with the URL the session id is also appended (example:URL + ;jsessionid=1234567).
  • Similarly from the client side whenever the second request comes in the client appends the URL again (Example: GET/Metavante;jsessionid=OAAB) to the request which the server has sent it previously

So in this way URL rewriting the client and server can maintain the session

Q: What do you go for ? Do you go for URL Rewriting? Do you go for Cookies? What is the Best Mechanism to maintain the session?
Ans:
For the first time server sends response back to the client, it employes both methods: It sends the Cookie and also sends the JSESSIONID to the URL and respose back to the client. The server really doesnt know the whether the client has disable or enable cookies thus it does the both things simultaneously. Now if the client has not disable to the cookies the client would have sent back a cookie in the next request and then the server would have known the "Ok, server seems to be "not disable the cookies" so let me continue using cookies now. So for request there on the server will only sends cookies . But now for example say "client has disabled cookies ! so server would not have sent back a cookie in the subsequent request, obviously server would have appended the JSESSIONID to the URL  and send back in the next request. Now when the server sees that there is no cookie, there is only jsessionid is appended to the url, it knows that this client has disabled cookie so then for the subsequent requests from there on it only sends the URL rewrting methods for maintianing the session. So basically this is how the session is maintained across the multiple requests.

Maintaining the sessions: 3rd Way is Hidden form parameters

This is using JSP'S.


Session Tracking - Cookies





Maintaining the sessions: there are 3 ways

1. Cookies
2. URL rewriting
3.


Session Tracking - Cookies




Cookies

Now we have seen that using the session id concepts: The server is able to maintain and manage sessions across multiple requests.
But how exactly the session id information is passed to the client and again inturn the session id sent back to the server right
There has to be some means the session id should be passed between the client and the server inorder to maintain the session
There are basically 3 ways which we can do it: One of the ways is through cookies
So Basically what happens is, the server creates a cookie for the client and sends across cookie to the client
Cookies are basically they are small files which are stored on the client machine. So this is the physical file actually some where in the client machine
Cookies will contain information about the client and everytime the client will send a request to the server and cookie information is also sent to the server from the client
Basically it sends the request and sends back to the client.

Example program for Cookies:

Steps:
1. create any folder (ex: cookiesex)
2. maintain the folder structure
3. set the classpath for tomcat server
4. deploy your application(your folder ex" cookiesex) in webapps folder under Tomcat server
5. start the server
6. execute your application in any browser


1. create any folder (ex: cookiesex)
2. maintain the folder structure
   1.  Home.html
   2. AddCookiesServlet.java
   3. GetCookiesServlet.java
   4.  create WEB-INF folder
         Under WEB-INF folder
        (a)  create classes folder
        (b)  create lib folder(optional)
        (c)  create web.xml file for configuration

   1.  Home.html
<!--Home.html-->
<html><body>
<form action="addcookie" method="get"> 
<pre>
Name : <input type="text" name="cname"/>
Value : <input type="text" name="cvalue"/>
<input type="submit" value="Add Cookie"/>
</pre>
</form></body></html>

2. AddCookiesServlet.java

package com.rajendra.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class AddCookieServlet extends HttpServlet {

public void service (HttpServletRequest req, HttpServletResponse res) 
throws ServletException, IOException {

String name=req.getParameter("cname");
String value=req.getParameter("cvalue");

Cookie c=new Cookie(name,value);

res.addCookie(c);

res.setContentType("text/html");
PrintWriter out=res.getWriter();

String output="<html><body>";
output+="Cookie Added Successfully <br/>";
output+="<a href='index.jsp'>Add One More</a><br/>";
output+="<a href='viewcookies'>View Cookies</a>";
output+="</body></html>";

out.println(output);
}//service
}//class

3. GetCookiesServlet.java

//GetCookieServlet
package com.santosh.servlet;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class GetCookieServlet extends HttpServlet {

public void service (HttpServletRequest req, HttpServletResponse res) 
throws ServletException, IOException {

res.setContentType("text/html");
PrintWriter out=res.getWriter();

out.println("<html><body><table border=1>");
out.println("<tr><th>Name</th><th>Value</th></tr>");

Cookie[] c=req.getCookies();
if (c!=null){
for (int i=0;i<c.length;i++){
out.println("<tr><td>"+c[i].getName()+"</td>");
out.println("<td>"+c[i].getValue()+"</td></tr>");
}//for
}//if
out.println("</table><br/><br/>");
out.println("<a href='Home.html'>Add One More</a><br/>");
out.println("</body></html>");
}//service
}//class

1. set the classpath
D:\\cookiesex>set CLASSPATH=C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar ;.;
2. Now compil e the servlet(java) programs to get the class files
D:\\cookiesex>javac -d . AddCookieServlet.java
D:\\cookiesex>javac -d . GetCookieServlet.java
3. Now copy the class files of AddCookieServlet.class, GetCookieServlet.class
4. paste into classes folder of WEB-INF folder

(c)  create web.xml file for configuration under WEB-INF folder
<!--web.xml-->
<web-app>
<servlet>
<servlet-name>ts1</servlet-name>
<servlet-class>com.rajendra.servlet.AddCookieServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ts2</servlet-name>
<servlet-class>com.rajendra.servlet.GetCookieServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ts1</servlet-name>
<url-pattern>/addcookie</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ts2</servlet-name>
<url-pattern>/viewcookies</url-pattern>
</servlet-mapping>
</web-app>
4. deploy your application(your folder ex" cookiesex) in webapps folder under Tomcat server

  steps for deploying  your application
 1. you can create war file also to deploy
preparing war file using cmd prompt

D:\\cookiesex>jar -cvf  cookiesex.war Home.html WEB-INF
(6) start the tomcat server
(7) deploy the servlet(servlet folder or war file into the webapps folder of Tomcat
(or) paste the ur application (ex: cookiesex.war) into the webapps folder of tomcat
(8)runing the servlet program
http://localhost:8888/cookiesex/Home.html

9) enter the name and value

10) click on Add  cookie button

11) click on viewcookies


3. hidden parameters ( this is in jsp)
Session Tracking - Cookies(
http://raj-servlets.blogspot.in/2013/09/session-tracking-cookies.html)

session management


How Session management works in the servlets? How Session is maintained by the server, in other words how the server is able to recognise and remember the client across multiple requests. Here you have to remember one thing is that Http is a stateless protocol. So Http in itself does not have the ability to remember the client. remember from where the request is come. So you said a request from your computer to a server ones and Http passes that request to the server.
But you when you send a second request from ur computer http doesn't know that the second request has come from the same computer from where the first request has come so basically HTTP is a stateless protocol. It does not have the ability to store the state of the client or the user.
so maintaining the state something that the server has to do so how does it perform.
For examples when you login your yahoomail, you enter your user name and password and you send a request to the yahoo server, the yahoo server gets you back the inbox and other email messages you have. So basically you click on one of the messages and you read on that message again navigate to various pages in that website and throughout this process server is able to remember you. So the first you enter your username and password and enter in your inbox and navigate across pages at each request the server knows that this is you is asking for details and server gives only your details so the server is able to remember the user.
How does it happen? so lets have a look.
Lets take a example where client A sends a request, say client A is trying to access the yahoo mail and it sends a request to the username of "raj" so now yahoo server takes the request and sees and understands that it is a new request from "raj" so let me store its state in the HttpSession object its basically creates a new HttpSession object (java object) (you can see in the figure ID#99 "raj") and it stores the value for that  HttpSession object with the associates with the user which has sent to the request so it is created an ID for the HttpSession and the id is 99 and it also associated id with the user which actually sent to the request so the user is "raj". So it has associated with the HttpSession object id 99 with the user "raj". Basically creates a HttpSession and sets the attribute "raj"  to this HttpSession  (you can see in the figure after 3 rd step) and HttpSession and then it gives back response to the client and it also gives back the id of the HttpSession created it also called as JSession Id.
So what happend when you sent a request to your yahoo mail inbox, the server has created a new HttpSession object and send back response that is nothing but your inbox page along with that is also send back to ID and that id will help the server to remember you in the future, so what happens now you got your inbox and you want to check your mail.
click on your one of your email messages so again a request is sent to the server
And now when a second request is sent along with the request even the ID #99 . Earlier server has sent back, the same id is sent to the server and now when the server gets second request, then its checks "Do I have a HttpSession object for this request for this user? Oh! and it checks with the user id #99 , ok it matches, with this user and associated with this id#99.
Now the server is able to validate the user and able to remeber the user this request so it knows that this is "raj" whose asking for his inbox details so it gives the message back to the user.
So in this the server of the Web Container manages the sessions across multiple requests



You may like the following posts:

HttpSession
1. cookies.
2. 
URL Rewriting

Tuesday, 3 September 2013

attributes in Servlets

attributes

Now we got one more thing that called attributes where you can store and retrieve data using attributes as well .
what is the difference between attributes and parameters( i.e initialization parameters)?
Ans: we have just seen that using parameters you can store some data and you can retrieve the data in your servlet code again im saying that in attributes you can store and retrieve the data.

1. what are the types of your attributes types are : Context attributes, Request attributes, Session attributes. This says nothing but about the life of the attributes. So Context attributes basically can be access through out the whole web application, where as Request attribute is only available for that particular request and Session attribute is valid until the session is finished so in that particular session only you can access this session attribute.
 Coming to parameters we have only two types of parameters: Context parameters and Servlet Init parameter.
So what are the methods by which we you can set value to an attribute: we have got the setAttribute(String, Object) method this is basically similar to a hashMap() where you put a value to a hashMap() using the key value pair so the key is nothing but the first parameter String and second parameter is nothing but value which is set to that attribute that is the actual object you want to store in the attribute. So basically on what object so you call this setAttribute() method whether you want to call Session object , Request object or Context object, basically you can set a value to the attributes using the key value functionality. Coming to parameters how do you set a value to initialization parameters, you can not dynamically set a value to the initialization parameters in your servlet code so this is one big difference you have to remember, you can only set the value to the initialization parameters ones that is only at the time of the web.xml , you can put in the value for that initialization parameters in the web.xml file. So if you have some attribute value which changes often say you want to set a value now and later on the value can change and you want to set another value in that attribute, so you can not do that using parameters, you can only do that using attributes because this is only one time process parameters at web.xml , at deployment time. But where as attribute you can get and set the values any number of times.

Return type of the attribute is Object, so basically you can store any type of the object in the attribute so you can set any type of the object and basically you can retrieve that object in the attribute. Where as the return type of the parameter is String, so you can store only string in a parameter, this is another big difference between attributes and parameters. If you want to store anything apart from String, you can not do that using initialization parameters even though you want to set that value only once through of the life of the servlet, you can not do that using parameters because return type is String, there is a object you want to store you have to do via attributes. And you can not do that using parameters.

So the method to get attribute or parameter, for attribute you use getAttribute() method, we can call either Context, Session or Request objects. Where as the parameters we use getInitParameter(String) method and passing the init parameter key name, servle context or servlet config object

Q: When do we go for attributes and parameters?
Ans:if u want to put in something which is only used once through out the application, that is a string you can use Init parameters. But there is something which can change frequently and which is not an objects you go for attributes


         attributes         parameters
types  Context, Request, Session Context, Servlet Init
Methods to set:  setAttributes(String, Object) We can not set init parameters
ReturnType  Object String
methods to get:  getAttribute(String) getInitParameter(String)

Servlet Config and Servlet Context objects

Servlet Config and Servlet Context


Fig: ServletConfig
In the init() method of the servlet class, the servlet has got access the two special objects called ServletConfig, ServletContext.

ServletContext

The ServletContext is an object , it is a java object basically as well as ServletConfig. The ServletContext object is only one for web application and ServletConfig is one for each servlet or JSP's.
so all the servlets in the application access the same ServletContext object but each servlet has got its own ServletConfig object. This is one important thing you have to remember. If you are accessing something ServletContext object you know that each and every servlet has got access to ServletContext object.
But Servlet2 does not have access to ServletConfig object of Servlet 1, Servlet2 is only got access to its own ServletConfig object.

ServletContext 
·         It is a interface is used to communicate with the servlet container. \
·         There is only one ServletContext for the entire web application and the components of the web application can share it. ServletContext object is created automatically by the Container as soon as you deployed the application
·         The information in the ServletContext will be common to all the components.
·         Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application.
When should we use ServletContext:
·         For example we have an Web application with two servlets, here one servlets needs to get some value (technical) from web.xml
·         That is all servlets in the web application can access these context values from the web.xml file
·         In case of ServletConfig , only particular servlet can access the values from the web.xml
Web application initialization:
  1. First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag.
  2. After creating the name/value pair it creates a new instance of ServletContext.
  3. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters.
  4. The servlet and jsp which are part of the same web application can have the access of the ServletContext.
The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters.
How to get the ServletContext object into our servlet class:
·         We can access the ServletContext object in 3 ways
In servlet programming we have 3 approaches for obtaining an object of ServletContext interface
1 st method:
ServeltConfig cf=getServletConfig();
ServletContext context = cf.getServletContext();
·         First obtain an object of ServletConfig interface
·         ServletConfig interface contain direct method to get Context object, getServletContext();
2nd method:
Direct approach, just call getServletContext() method available in GenericServlet [pre-defined].  In general we are extending our class with HttpServlet, but we know HttpServlet is the sub class of GenericServlet.
Public class Demo extends HttpServlet
{
Public void doGet/doPost(----))
{
//….
}
ServletContext ctx = getServletContext();
}
3rd method
We can get the object of ServletContext by making use of HttpServletRequest object, we have direct method in HttpServletRequest interface.
public class Demo extends HttpServlet
{
public void doGet/doPost(HttpServletRequest req,-)
{
ServletContext ctx = req.getServletContext();
}
}

How to Retrieve Data from ServletConfig interface object
ServletContext provide these 2 methods, In order to retrieve the data from the web..xml [ In web.xml we have write <context-param>tag to provide the values, and this <context-param> should write outside of <servlet> tag as context should be accessed by all servlet classes ].
In general database related properties will be written in this type of situation, where every servlet should access the same data.
·         public String getInitParameter(“param name”);

·         public Enumeration getInitParameterNames();



What is the use of ServletConfig and ServletContext objects?
Ans:
One thing you can definately do is fetch your initialization parameters.
So what are init parameters?which seen previously in the web.xml that you have a "webapp" element and within that you have number of servlet and servlet mapping elements. i told you that apart from servlet and servlet mapping elements you will have a number of other elements in web.xml within the webapp folder. So one of those are the init parameter elements  so init parameter elements basically whatever initialization parameters you want to put in your servlets or  your apps specifically you can put that initialization parameters values in the web.xml in the init parameter tag .

For example: you want to store the path to the data source URL , you can put that data source URL init parameter element. So you can put init parameter and you can give the parameter name data source. So its start the data source tag put the value for the data source and you close the data source tag. So we have two types of init parameters here Context init parameters here and Servlet init parameters.

Differece beteen Context init parameters and Servlet init parameters?

Ans:
1.  we have seen that Context is one per application whereas servlet is one per servlet  scope for Context init parameters tipically becomes to the whole web container where as the scope for the init parameter is specific to the Servlet or JSP whichever servlet within you write the init parameter so basically when you write the init parameters for a Context init parameter you put it under main webapp element and you do not put inside the any servlet element tag but when you are writing the init parameter servlet you have to put it within the servlet element tag.
How do you get the init parameter value in your servlet code or your init() method so the code you write to get the init parameter is getServletContext() so you basically call these methods getServletContext() and again call the method on so this is going to return the context object and on that Context object you say Context object . get init parameter valueget similarly for servlet you say getServletConfig() so this will give you the instance of the Config object on which you can call the init parameter.

next the deployment descriptor: As I have told you it  goes directly within the webapp element but not within a specific servlet  element but where as Servlet Init parameters the entry goes to the servlet element so whatever servlet you want init parameter to be available you put this init parameter entry in that particular servlet element.

Context init parameters Servlet init parameters
Scope Scope is Web Container Specific to Servlet or JSP
Servlet Code getServletContext() getServletConfig()
deployment Descriptor within the webapp element but not  within a specific <servlet> element within the <servlet> element for each specific servlet