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.

doPost()and doGet() methods in Servlet

GET/POST

We have seen that when the type of request is get, then service() calls the doGet(), when the type of request is post, then service() calls the doPost(). But the question is:

When do we go for doGet() and When do we go for doPost()?
Ans:  When we use doGet() method:  get HTTP request only has a request line and HTTP header where as a post has a request line HTTP and header and also has a HTTP body.
For example when you type your yahoomail and try to get your emails and you pass the username and password in yahoo Login screen so how are these username and password  passed to the server. You have seen that these are passed in the form parameters and in the form elements of the request . So when you are going for these form elements are appended to the end of the URL so whaever URL you are sending it the form parameters are appended to that URL and send it across to the server so the form parameters whatever information you are passing to the server that is visible in the URL  when you are going for a Get().

But in the case of Post(): the form parameters are passed in the HTTP body, and these HTTP body is not seen by anyone, and it maintains the secret which can not seen by anyone so the form parameters are here send in the HTTP body but not in the URL (Which is seen by everyone).

next point the size: so although you can send the information using Get() appending it to the end of the URL, the amount of data which you can send using Get() method is limited, you can send very less amount of data to implement a Get() but whereas in a Post() you can send large amount of data to the server because we send the data in the HTTP body but not on the request line.

When should we use Get() and when should we use Post()?
Ans: whenver something to fetch something from server you go for a doGet() method, and when you want to post something to the server, you go for doPost().

Example: if you want to search servlet in google search: so you go to Google .com you type "servlet" in the search text box and you type on search so the server actually gets you back with all search elements for the servlets so you are tring to fetchi something from server right? in this case you are using the doGet() method.

Now take another example: when you are filling online application form, then you will enter lots of fields and then you submit that form to the server, in this case you are actually you  are filling form and submiting the data to the server. So when you want to submiting to the server you use a Post() method.

So basic term rule is when you want to fetch something from the server go for Get() method, when you want to post something to the server go for doPost() method.

but there is one condition is there you know that using Get() you can pass some parameters to the server But if the typ of the parameters sending a sensitive the eventhough the amount of parameters we are sending less you should go for a Post() method. For Example when you are tring to get your email, passing username and password in the yahoo log on screen and click on go to my email by clickin log on button and that you will all you get your messages , your particular email address so here eventhough you are trying to get something (email) from the server (yahoo server) you should be using doPost() method because the type of information you are sending is 'sensitive' information. When you go for a get, the username and password would have been appended to the end of the URL and send it across to the server and everyone can see this username and password but you dont want anyone to see your username and password which you are using so this information is sensitive. So all sensitive transactions whaever the amount of data, whatever the type of data transaction you are doing get or fetch you should go for doPost() method because in the Post() the data is sent in the HTTP body , not be seen by anyone


                                     doGet() doPost()
HTTP request The request contains only the request line and HTTP Header Along with the      request line and header it also contains HTTP body


Parameter The form elements are passed to the server by appending at The form elements are passed to the server in the body of the HTTP request
passing the end of the URL

size The parameter data is limited (the limit depends on the container we can send large amount of data to the web server

Usage go get(fetch) information from the server to process the sent data

Different Methods of Servlet (init(),service(),doPost(),doGet(),destroy())

Different Methods of Servlet

1. init() method:

    init() is called before any request for the servlet can be handled even before any client request can be served the init() is called and init() is called by the Web Container or Servlet Engine.
What init() is for:  to initialize your servlet (it can be data source, to connect your data base or any such initialization you can perform , and
what do you mean by initialization? it is a one time process that you dont want to initialize everytime every  client request you dont want this particular thing to happen )before handling any client requests. And it happens only once in life time of servlet.

Now my doubt is we do have a constructor for servlet? when you talk about the java, generally we all put the code for initialization stuff in the constructor of the class right ! then why do we use init() for initialization in servlet? why can't we use initialization in constructor?  my answer is init() has to access special objects (servletContext, servletConfig) and you generally you can have access those objects in your init() during initialization. These two special objects can be accessed in init() method only but in the constructor.So thus the reason we have to use init() to access those objects

Frankly speaking you cant write the constructor in servlet it will take a default constructor implementation given by the jvm.
We know that if we dont add a constructor to your class the JVM will put a default constructor to your class with no implementation that is blank constructor to your class
so container will take the default implementation of the constructor.
We can override the init() method, any kind of initialization code you want to perfom you can override the init() method else you dont override

2. service():

When service() method is called?
Ans: It is called for every request that comes in for particualr servlet. For example when you type the yahoo login servlet, everytime a person makes a request to yahoo login servlet, the service() method of this login servlet is called.

Why do we use service() in servlet?
Asn: to determine which HTTP method(doGet() or doPost()) should be called.

Can we override the service()?
Ans: No, Because the only thing that the service() is to do is to determine the HTTP methods, to write the HTTP method, to invoke your servlet class based on the type of request client has sent. so you dont really need to override it. Whatever functionality you required for the service() method that is already presented in the HTTPServlet.

3. doGet() or doPost() methods

basically these two methods are used to put all your business logic. The type of request was get, we override the doGet() methods. When the type of request was post, then we override the doPost() method.

When doGet() or doPost() methods are called?
Ans: It is called by the service() method based on the type of request and you put your business logic.

Do you override the doGet() and doPost() methods?
Ans: Yes, Because you have writted your servlet to provide some business logic some dynamic logic to be presented to the end user and it is only place you put your business logic.
Basically doGet()you actually can call other classes and other methods for that your business logic is not in single place, write across multiple classes and it is easier to understand.

4. destroy() method?
when the session time is out. The Web Container calls a destroy() method

Web Container supports Multithreading?
The container runs multiple threads process multiple requests to a single servlet

Fig: Multithread:
Lets take a example you login to yahoomail.com, and sending email, user name and password and the yahoomail servlet actually will give you back your inbox all your messages. Lets say client A login through yahoomail and sends username "abc" so What the Web Container does? The Container sponsers Thread A for client A and passed in the request as "abc". Now at the same time client B makes a request to the yahoo servlet and passing the request username as "xyz" to Thread A so now Web Container sponsers another Thread B for the client B and pass the request "xyz" to the Thread B so Thread A process the request "abc" and create a response object and send back to the response for client A.
Similar fashion Thread B takes this request "xyz" and creates a response object and process the request send back to the response for client B.

One thing you have to note that these two different threads (Thread A and Thread B) are response but the request and response objects are different and they do not share the same request and response objects. So Thread A has its own request and response object and Thread B has its own request and response object. Basically how the multithreading works for a servlet.

You may like the following posts:

Sunday 1 September 2013

Life cycle request, response?

Life cycle request, response?
Basically servlet state is initialized state. Does not exist state is void state


When the first time request comes from the client.
the constructor called on the servlet, ones the lifetime of a servlet, the constructor() and init() are called on the servlet
and ones the init() is called servlet moves from "Does not exist" to initialized state and ready to be used by other requests
for every subsequent requests that comes in service() method is called and servlet still stays in the initialized state
when the destroy() is called again servlet goes back to from initialized state to does not exist state
All these methods (constructor(),init(), service(), destroy()) are called by the Web Container or Servlet Engine
We can see the servlet Hierarcy below figure



At the top of this hierarchy, Servlet is a interface
GenericServlet implements the Servlet interface and it is a abstract class i.e GenericServlet implements Servlet
if we do not override the init() method, if we dont have any initialization code in your servlet. So when you do not override the init() it takes the default implementation from the Generic
Servlet
Now HttpServlet extends the GenericServlet again it is a abstract class. Here if you do not override the service() method the default implementation from HttpServlet is taken
And in the end 'Your Servlet' this is the servlet which you will code in the servlet class which you actually write should extend the HttpServlet and this is concrete class. And this is the place where you implement the methods that is either doGet() or doPost()



Different Methods of Servlet 

1. init() method:

    init() is called before any request for the servlet can be handled even before any client request can be served the init() is called and init() is called by the Web Container or Servlet Engine.
What init() is for:  to initialize your servlet (it can be data source, to connect your data base or any such initialization you can perform , and 
what do you mean by initialization? it is a one time process that you dont want to initialize everytime every  client request you dont want this particular thing to happen )before handling any client requests. And it happens only once in life time of servlet. 

Now my doubt is we do have a constructor for servlet? when you talk about the java, generally we all put the code for initialization stuff in the constructor of the class right ! then why do we use init() for initialization in servlet? why can't we use initialization in constructor?  my answer is init() has to access special objects (servletContext, servletConfig) and you generally you can have access those objects in your init() during initialization. These two special objects can be accessed in init() method only but in the constructor.So thus the reason we have to use init() to access those objects

Frankly speaking you cant write the constructor in servlet it will take a default constructor implementation given by the jvm.
We know that if we dont add a constructor to your class the JVM will put a default constructor to your class with no implementation that is blank constructor to your class
so container will take the default implementation of the constructor.
We can override the init() method, any kind of initialization code you want to perfom you can override the init() method else you dont override

2. service():

When service() method is called?
Ans: It is called for every request that comes in for particualr servlet. For example when you type the yahoo login servlet, everytime a person makes a request to yahoo login servlet, the service() method of this login servlet is called.

Why do we use service() in servlet?
Asn: to determine which HTTP method(doGet() or doPost()) should be called.

Can we override the service()?
Ans: No, Because the only thing that the service() is to do is to determine the HTTP methods, to write the HTTP method, to invoke your servlet class based on the type of request client has sent. so you dont really need to override it. Whatever functionality you required for the service() method that is already presented in the HTTPServlet.

3. doGet() or doPost() methods

basically these two methods are used to put all your business logic. The type of request was get, we override the doGet() methods. When the type of request was post, then we override the doPost() method.

When doGet() or doPost() methods are called?
Ans: It is called by the service() method based on the type of request and you put your business logic.

Do you override the doGet() and doPost() methods?
Ans: Yes, Because you have writted your servlet to provide some business logic some dynamic logic to be presented to the end user and it is only place you put your business logic.
Basically doGet()you actually can call other classes and other methods for that your business logic is not in single place, write across multiple classes and it is easier to understand.

4. destroy() method?
when the session time is out. The Web Container calls a destroy() method

Web Container supports Multithreading?
The container runs multiple threads process multiple requests to a single servlet



Fig: Multithread:
Lets take a example you login to yahoomail.com, and sending email, user name and password and the yahoomail servlet actually will give you back your inbox all your messages. Lets say client A login through yahoomail and sends username "abc" so What the Web Container does? The Container sponsers Thread A for client A and passed in the request as "abc". Now at the same time client B makes a request to the yahoo servlet and passing the request username as "xyz" to Thread A so now Web Container sponsers another Thread B for the client B and pass the request "xyz" to the Thread B so Thread A process the request "abc" and create a response object and send back to the response for client A. 
Similar fashion Thread B takes this request "xyz" and creates a response object and process the request send back to the response for client B.

One thing you have to note that these two different threads (Thread A and Thread B) are response but the request and response objects are different and they do not share the same request and response objects. So Thread A has its own request and response object and Thread B has its own request and response object. Basically how the multithreading works for a servlet.