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

Request and Response objects in Servlets

Request and Response

We know that when send the request to the server, the Web Container invokes and calls the servlet methods and servlet sends the response to the client. But now assume that the servlet does not have the ability to serve the request of the client , now what happens.


Fig: Response.jpg

You just see the Figure: the request comes and the servlet serves the request and it sends the resource to the client.
Now lets see the if the servlet does not serve the request, now the servlet can not serve the request,


For Example: i have created a website called abc.com and i have got a lot of users for the web site, after some couple of years i want to change my name of that website abc to xyz.com. But i have developed lot of clients and i dont want to loose those clients so what I want to do is now my abc servlet can not serve the request from the client but whenever a request comes to abc servlet and I want the request can be redirected to xyz servlet so i dont want the client go get error page for my previous name abc.com. I know that abc servlet can not serve the request, and I know that xyz servlet can serve the request. I want people to talk xyz servlet now instead of abc servlet.

My abc servlet can not serve the request but "does the servlet know who can serve the request?" it knows because xyz servlet can serve the request, it now sends the response back to the client and it talks the xyz servlet and sends the response back to the client.
There are two ways which can do this process:
we can use the following ways for that purpose
1. send redirect
2. request dispatcher
Now lets talk the difference between them:

When you implement a Send Redirect the servlet actually sends back response to the client (web Browser) and says that it can not serve the request but it knows the xyz servlet can serve the request, so please send the request to xyz servlet so the web browser now gets this response from servlet abc and sends another request to servlet xyz and finally gets the resource from xyz servlet. But really being a end client dont know that response has come back from abc and web browser has send another request to xyz, but you dont know that these two steps process have happened.
From your(end client) prospective you only types abc.com and you got some response, but you dont knw that these two steps process have been taken to get the response so that is send redirect.

What happens Request Dispatcher?
Ans: In Request Dispatcher basically the servlet itself (the abc servlet itself) will forward the request to xyz servlet and the response will send back to xyz servlet to the client, so here there is no failure response send back to the browser and browser send back another request to the xyz servlet but the abc servlet itself forwards the request to xyz servlet and xyz servlet forwards the response to the client so that is Request Dispatcher.

When should we use Send Redirect and Request Dispatcher?
Ans: Basically you can use Request Dispatcher only when the other servlet which can serve the request of the client and lies in the same web application, if the other servlet in the same web applicaiton only in that scenario you can use the request dispatcher. But if the other servlet is same in the web application only in that scenario you can use a Request Dispatcher. But if the other servlet is outside this web applicaiton, or if the servlet is in other webapplication then you have to use send Redirect because it has to make another request, it really communicate with the other servlet which lies outside the web application. And finally the servlet abc really know who can serve the request sent by the client, then it sends the Error page to the client.

For example: we know that sunmicrosystem was merged in Oracle organisation, but still if you type the sunmicrosystem.com in the web browser it will be redirected to oracle.com.