Saturday 13 April 2013

JSP


                                      JSP
 Scriptlet: -In this, we use java code i.e.
request.getparamater (" property name");
=> When the object is stored in the Request scope. i.e.
out.println (request.getparamater (" property name"));
 Jsp expression: - In this,
<%= request.getparamater ("property name")
=> This is used instead of out.println ();
 Action tag: - In this
<jsp: getproperty property="name as in form" name="key for request scope">
 Custom Tag: -
<c: out> in cout user either jsp expression or ELExpression
Page Scope: For every jsp one page context object is created. When java object is used by single jsp then those cases we are going to use Page Scope.
Request Scope: Java object is used by multiple servlets.ie multiple Servlets are involved while processing a single request then those cases use request scope. Multiple Servlets involved means when you use include or forward the same request object given to included Jsp. i.e. Servlet chaining.
Session Scope: Java object is used by multiple Servlets. I.e. multiple Servlets are involved while processing a Multiple Requests (not single request). In wizard style every time when we click on Next Button it becomes a new request. Then those cases use session scope. Each time when you click on Next Button it is stored in the session scope in the wizard style when we mention scope is session.
Note: In wizard Style every time when you click on Next Button it becomes a new request.
Then it creates a new Request and Response objects. So if you use request scope in wizard style then it create a new request every time when we click on Next Button. Then what ever java object in request scope is removed every time when you click Next Button. So, In Wizard style uses session scope. In session scope we are going to store client specific information.
Means From Hyderabad we fill data in the form belong to our data. And our friend fill the data from Bangalore belong to his specific data. For every browser/client/user one session object is created. So for every user specific data is stored in their own specific session object. After closing the browser the session object will be removed. In between if you want stored the data in the DATABASE before closing the browser. For one browser/client/user one session object is created. For every browser/client/user one session object is created. That session object is pointed to implicit variable Http Session. Client specific information is stored in the session scope.
Application Scope: - When we deploy the application in the server. Then ServletContex (application) object is created. This object is pointing to implicit variable in jsp ServletContex context. The common data belong to entire application is stored in the Application scope. Client specific information is stored in session scope (i.e. for one browser one session object is created. whatever person is using the browser that person is stored in that browser specific session object. For every browser one session object is created) .The java object in the application scope you can get from anywhere and from any flow in entire Application. SESSION SCOPE store client specific information. APPLICATION SCOPE store common data belong to entire application.
DEFINATIONS FOR SCOPES: -
Page: - If a java object is used by a single jsp during executing of jsp then we need to use page scope.
Request: - when multiple Servlets are involved in processing a single request has to share the same java object then we need to use request scope.
Session: - when java object holds anything specific to the client and if the object is required while dealing with multiple request (not single request) then we need to use session scope.
Application: - Application object holds the data that is not specific to the client (It holds global data) and this is required while dealing with multiple requests.
REMEMBER: - While dealing with multiple requests (In wizard style), we can go for Session scope or Application scope.
JSP ELEMENTS: -
Template Text: - Whatever we write in the jsp is displayed in the browser.
Scriptlet: - whatever we write in this, is placed in jspService () method. In this we are going to write java code. Scriptlet by default support java language to support any other languages you write code page directive in the top of jsp. For support java script in the scriptlet you are going to write as
 <%@ page language="javascript" %> in the top of the jsp.
Jsp Expressions: - Use instead of out.println (Object or string). out.println () does not support null value as parameter so we are going to use Jsp expressions instead of out.println ();
Jsp Declarations: - for declaring instance variables, instance methods, static variables, static methods. But calling of methods from Scriplets only.
Jsp Directives: - For importing java packages and java classes. And for supporting diff languages in jsp
Jsp Action Tags: -  
 <jsp:useBean>
 <jsp:setProperty>
 <jsp:getProperty> 
Jsp Custom Tags: -
El Expressions: -
According to the Microsoft specification not going to write the java code in the jsp. So by using Action Tags and Custom Tags we are going to eliminate the java code form jsp.

JSTL
JSTL supports expression language (EL expressions).
EL Expressions are provided for an alternative to jsp Expressions.
EL Expressions are used for only for Scoped variables.
Key of the attribute is called as scoped variable in case of EL Expressions (key place main role in case of EL Expressions).
<Html>
  <% pageContext.setAttribute ("vone","SANTOSH");
<-- here we write java code in jsp. So to avoid java code form jsp                                                      use<c:set> tag-->
  pageContext.setAttribute ("vtwo","SIVA");   %>
 <Body>
 <c:out value="${vone}"></c:out><br/>
 <c:out value="${vtwo}"></c:out></br>
 </body>
</html>
USE <C:SET> =>
<c:set var="vone" value="SANTOSH BHAI" scope="page"></c:set>
 <c:set var="vtwo" value="SIVA REDDY" scope="page"></c:set>

EL Expressions supports various operators that are supported by programming languages like c, java.
<% pageContext.setAttribute ("vone","100");
        pageContext.setAttribute ("vtwo","200"); Or
%>
Here you observe one thing is set integer value as string here concentrate on this point
<c:set var="vone" value="100" scope="page"></c:set>
<c:set var="vtwo" value="100" scope="page"></c:set>
<c:out value="${vone*vtwo}"></c:out>
 <c:out value="${vone*vtwo}"></c:out>
 <c:out value="${vone*vtwo}"></c:out>
Like in jsp in EL Expressions also some implicit variables are there. Some of them are
1) pageScope
2) requestScope
3) sessionScope
3) applicationScope
5) param
6) header
Note: Suffix with scope is very important

PROGRAM: -
<html>
<c:set var="vone" value="100" scope="page"></c:set>
<c:set var="vone" value="200" scope="request"></c:set>
<c:set var="vone" value="300" scope="session"></c:set>
<c:set var="vone" value="400" scope="application"></c:set>
<body>
<c:out value="${vone}"></c:out><br/>
<c:out value="${requestScope.vone}"></c:out><br/>
</body>
</html>

Here variable ‘vone’ we can keep it in all scopes. So when we print as <c:out value="${vone}">
From which scope it takes values. Jsp compiler by default follow one order the order is first check in pageScope, in key available in page scope and then prints the value. If the key is not available in page scope. Next it checks in request, session and application, and then prints the values.
If we mention scope like this.
 <c:out value="${requestScope.vone}">
Then prints the value for that particular scope variable.
<c:out value="${requestScope.vone}">
<- If you mention scope like this it improves the performance and more readable->
--------------------------------------------------------------------------
<jsp: useBean id="idOne"  class="com.siva.Trail" scope="session"/>
            (or)
<c:set value="com.siva.Trail" var="idOne" scope="session"></c:set>

Internally it creates object as like this
         Trail idOne=new Trail();
So when you print as
<c:out value="${session.idOne}"></c:out>
Then it prints the address of Trail object
 When you print as
 <c:out value="${session.idOne.propertyName}"></c:out>
Then it calls getter method and print property value
Sample Program for Scopes: -
Addressbean: -
public class Address {
        private String street;
        private String city;
        private String state;
}
Employeebean: -
public class EmployeeJB {
        String eno;
        String ename;
        String esalary;
        Address address;
}
Scopestest.jsp: -
<html>
 <body>
 <%  
Address a=new Address();
        a.setCity("NELLORE");
        a.setState("ANDHRAPRADESH");
        a.setStreet("PETA SATRAM ROAD");
        EmployeeJB employee=new EmployeeJB();
        employee.setEname("SIVA");
        employee.setEno("47");
        employee.setEsalary("1000000000");
        employee.setAddress(a);
        request.setAttribute("keyvar",employee);  
 %>
  <c:out value="${requestScope.keyvar.eno}"></c:out><br/>
  <c:out value="${requestScope.keyvar.ename}"></c:out><br/>
  <c:out value="${requestScope.keyvar.esalary}"></c:out><br/>
  <c:out value="${requestScope.keyvar.address.street}"></c:out> <br/>
<c:out value="${requestScope.keyvar.address.city}"></c:out> <br/>
<c:out value="${requestScope.keyvar.address.state}"></c:out> <br/>
</body>
</html>
How to keep collections object in scope variables::::
Using of vector: -
<html>
<body>
  <%
Vector vector=new Vector();
       Address address1=new Address();
        address1.setCity("Nellore");
        address1.setState("Andhrapradesh");
        address1.setStreet("Peta Satram Road");
        Address adress2=new Adress();
        address2.setCity("Karimnagar");
        address2.setState("Telanagana");
        address2.setStreet("Kanagarthi");
        vector.add(address1);
        vector.add(address2);
        request.setAttribute("vectorvkey",vector);   %>
   <c:forEach var="adr" items="${requestScope.vectorvkey}">
   <c:out value="${adr.city}"></c:out><br/>
   <c:out value="${adr.state}"></c:out><br/>
   <c:out value="${adr.street}"></c:out><br/>
   </c:forEach>
</body>
</html>
Using Of Hashtable: -
<html>
<body>
<%  
        Hashtable hashTable=new Hashtable();
        Address address1=new Address();
        address1.setCity("Nellore");
        address1.setState("Andhrapradesh");
        address1.setStreet("Peta Satram Road");
        Address adress2=new Adress();
        address2.setCity("Karimnagar");
        address2.setState("Telanagana");
        address2.setStreet("Kanagarthi");
        hashTable.put("keyOne",address1);
        hashTable.put("keyTwo",address2);
        request.setAttribute("hashtableKey",hashTable); 
%>
<c:forEach var="adr" items="${requestScope.hashtableKey}">
<c:out value="${adr}"></c:out>
<c:out value="${adr.key}"></c:out><br/>
 <c:out value="${adr.value}"></c:out><br/>
 <c:out value="${adr.value.city}"></c:out><br/>
 <c:out value="${adr.value.state}"></c:out><br/>
 <c:out value="${adr.value.street}"></c:out><br/>
 </c:forEach>
</body>
</html>
Output Is: -
keyOne=com.siva.Adress@7283b2 keyOne
// <c:out value="${adr}"></c:out> prints key and value both
keyOne
//<c:out value="${adr.key}"> prints Key of adress object in hashtable object
<c:out value="${adr.value}"> print the reference of adress                                                            object in hashtable object
Nellore
<c:out value="${adr.value.city}"> print the value in address object
Andhrapradesh
Peta Satram Road

CUSTOM TAGS by sumanth
In the jsp we are going to use custom tags. By using custom tags we are able to remove the java code from jsp. But some time it is not possible to remove java code form jsp by using action tags. So we are going to use custom tags..
To iterate the ArrayList in the jsp there is no Action tags. So to iterate ArrayList in jsp we use Custom tags.
To use custom tags first
 1) We need to identify what are the tags as part of our tag library
2) You need to identify the functionality of tags. Identify the functionality that needs to carry out by every tag.
NOTE: - The jsp compiler uses the TLD files to find which tag is mapped to which tag handler class.
In the tld file <taglib-version> tag indicates the version info about our tag library.
In the tld file <jsp-version> tag is used to specify which version of jsp container is supported our taglibrary. This usp version tag specify from which lower version of jsp, is supported for this tag library.
How to use tld fils in our project?
1) Copy the library files in lib folder of our project.
2) Copy the required tld files into the WEB-INF directory.
3) The information regarding the taglibrary must place inside the web.xml file...
4) To use tag library in our jsp we have to provide the jsp page directive (taglib)
FLOW: When you use tag in the jsp then based on prefix of tab it identify the uri in the jsp pagedirective. Based on the uri it goes to web.xml file. In the web.xml file if uri is matched then find the tld file in web.xml file.Then go to WEB-INF,here tld file entry is there. In the tld file class name is there.the .class file file for that class is in lib folder. Then it executes the class and do the operations for that tag...
In the tagHandler class doEnd() will return  EVAL_PAGE (or) SKIP_PAGE. Compulsary taghandler class must return any of the above constant. If doEnd() tag method return EVAL_PAGE. After tag is evaluated or executed the jsp complier can process the other tags which are available in the jsp.
If taghandler class returns SKIP_PAGE after tag is evaluated the jsp compiler will discard all other tags which are available in the jsp.
If anyone develops the tag library most of the time they return EVAL_PAGE only.
FOUR TYES OF TLDS
1) c.tld, c-rt.tld: All tags that are required to project is placed in the tld.
2) sql.tld, sql-rt.tld: All tags which are required to interact wt DB
3)  fmt.tld, fmt-rt.tld: To develop I18N applications.
4) x.tld,   x-rt.tld: This tag library consist of set of tags to read the contents form xml files
<c:out value="SANTOSH"></c:out>
Here SANTOSH is static text .For static text better to use TemplateText. Because for custom tags lot of code will be generated internally.
VERY IMPORTANT POINT
Most of the times when data is given to View by controller. The data will be placed in any of the scope (page, request, session, application). Mainly the core tag library deals with getting data from the scopes and iterates them and display result s to the user.
As part JSTL it supports EL Expressions. Jstl EL Expressions will support only scoped variables. EL Expressions are replacement of Jsp Expressions
NOTE: We cannot use EL Expressions on the java variables.
<c:out value="${vone+vtwo}"></c:out>
In the above <c:out> tag vone, vtwo variables assume are not in any of the scope. And if the variable is participated in arithmetic expressions it returns '0' value.
SET TAG: set tag is used to create the object and add the object to a specific scope.
<c:set var="Vone" value="100" scope="request" />
 Default scope is page.
When ever set tag is evaluated it create a variable Vone and store the data inside the Vone variable. And Vone variable will be added to request scope with key Vone.
${ } : This type of syntax is called as EL Expressions...
NOTE: param is the implicit variable. Using this implicit variable we can read the data from HTML form.
VECTOR EXAMPLE
First time when for Each tag is evaluated it gets the first element from collection object, The element reference will be stored in a variable obj. This variable will be added to the page scope. we can get this object by using out tag.
<c:forEach var="obj" items="${requestScope.empdet}">
  <c:out value="${pageScope.obj.name}"/><br/>
  <c:out value="${pageScope.obj.street}"/><br/>
  <c:out value="${pageScope.obj.city}"/><br/>
  <c:out value="${pageScope.obj.state}"/><br/>
</c:forEach>
In the code forEach tag is evaluated and it gets the first object form vector and it is assigned to variable obj. This object will be added to the pageScope with key obj.
We have use the cout tag to get the data from pageScope whose key is obj. The same process will be repeated for all the elements which are available in object.
Every time it will execute for each tag page Context object will be refreshed with the objects....
<c:forEach var="i" items="one,two,three,four,five">
    <c:out value="${i}"/></c:forEach>
          When the forEach tag is evaluated the forEach tag checks weather items object is separated with the separator delimiter, it is , operator then forEach tag gets the value which is available before the coma operator.

Session Tracking Techniques
HIDDEN VARIABLES
COOKIES
SESSIONS
URLREWRITTING

Http, Https Protocol is a stateless protocol. All servers are developed by supporting for http, https protocols. So all servers are stateless because http, https are state less protocols.
Https for security => security available by the process of. If network administrator is did as server support https protocol. So when you send the request to the server. Then server encrypts the data and does the process. Then server gives response back to the client with certifications. Then based on the certifications client (Browser) decrypt the information. This is the process when you use https protocol.
If the protocol needs to behaves as stateful protocol it uses the following techniques.

V IMP NOTE: Sometimes we need to capture the data from the user using multiple forms (i.e. by Wizard style)
When you click on NEXT BUTTON each time it is new request. (That is in wizard style)
FLOW IN WIZARD STYLE:-  You send the request to f1.jsp . After sending the request to f1.jsp it is displayed in browser and you fill the form with some fields and click on next button. When you click on next button again request goes to server and request goes to f2.jsp
In f1.jsp the fields are sno, sname and in f2.jsp the fields are fathername, adress. When you click on next button i.e. before request goes to f2.jsp--- The browser will capture the details entered by user in f1.jsp and send the request to server for executing ftwo.jsp
NOTE: The server has placed user details inside the request object. This request object will be removed from the user after ftwo.jsp is proceeding. After ftwo.jsp is processed the server will remove the request, response objects and displays the ftwo.jsp in browser. After user has filled the data in the ftwo.jsp form the user will click on store button. Now new request will send to the server for procession store.jsp.
Now the server will execute the store.jsp program. This program captures the data sno, sname, fathername and address from the request object and stores the info in DB. But the current request object is holding the information about fname and adress. It does not consist of sno information and sname informatio. Because of this reason we will get null values.
To rectify this problem we will goes to 1) Hidden variables 2) cookies 3) sessonns 4)urlRewritting

HIDDEN VARIABLES
Using this approach or technique. When you send the data to the server our application captures the data and sends back the same data to the client program once again in the form of hidden variables
fone.jsp
<html>
 <body>
<form action="hidden2.jsp">
 STUDENT NO::<input type="text" name="sno"><br/>
 STUDENT NAME::<input type="text" name="sname"><br/>
 <input type="submit" value="NEXT">
 </form>
</body>
</html>
ftwo.jsp
<html>
<body>
<form action="hidden3.jsp">
<input type="hidden" name="sno" value="<%=request.getParameter("sno") %>"><br/>
<input type="hidden" name="sname" value="<%=request.getParameter("sname") %>"><br/>
 FATHER NAME::<input type="text" name="fname"><br/>
 ADRESS::<input type="text" name="address"><br/>
 <input type="submit" value="STORE">
 </form>
 </body>
</html>
Store.jsp
<html>
 <body>
<%
     String studentno=request.getParameter("sno");
     String studentname=request.getParameter("sname");
     String fathername=request.getParameter("fname");
      String address=request.getParameter("address");
     %>
   <%=studentno %><br/>
   <%=studentname %><br/>
   <%=fathername %><br/>
   <%=address %><br/>
  </body>
</html>
Using of the hidden variables or hidden fields for huge amount of the data is not recommended. It reduces the performance of the application.
NOTE:  Hidden variables cab be used to store for very less amount of data. Generally we use this in search criteria.
Most of the developers prefer using of hidden variables. Because this technique will not consume the server resources (Will not create any objects or memory in the server).
When you using hidden variable you observe the URL and VIEWSOURCE (You observe the values of the hidden variables).

COOKIES
A Cookie is a small piece of information set by server on the client program. A cookie is available in client pc. Cookie concept is also for maintaining the state like as hidden variables.
A Cookie will be having name and value i.e. cone=valueOne.
In the earlier version there is no restriction on no of cookies set by server on client pc. But now new version of browser there is a restriction on no of cookies.
If the cookies are available with the client and when ever client sends the request to the server the cookies will send back to the client program.
Whenever server sets a cookie on the client. Client uses the domain name of the server to store the cookies of to categories the cookies in the client program.
In the old applications most of the customers does not like using of cookies. Because of security reasons. In the latest browsers all the security related problems are rectified. Because of this reason in the latest applications has started using cookies...
In java to represent cookies we use a class   javax.servlet.http.Cookie.
Note: - Here two types of cookies are there they are
1) Default cookies (created by server) 
2) Developer created cookies.
NOTE: - Sessions concept depend on default cookies .Example of default cookie is JsessionId cookie.
REQUIREMENT: - Develop a jsp program which will be able to create two cookies and set them or place them inside the client program.
PROGRAMG FOR HIDDEN VARIABLES?
fone.jsp
<html>
<body>
 <form action="hidden2.jsp">
STUDENT NO::<input type="text" name="sno"><br/>
STUDENT NAME::<input type="text" name="sname"><br/>
<input type="submit" value="NEXT">
</form>
</body>
</html>
ftwo.jsp
<html>
<body>
  <%
   String studentno=request.getParameter("sno");
    String studentname=request.getParameter("sname");
    Cookie c1=new Cookie("ckone",studentno);
    Cookie c2=new Cookie("ctwo",studentname);
      response.addCookie(c1);
      response.addCookie(c2);
   %>
<form action="hidden3.jsp">
<!--  <input type="hidden" name="sno" value="<%=request.getParameter("sno") %>"><br/>
<input type="hidden" name="sname" value="<%=request.getParameter("sname") %>"><br/>
 -->
FATHER NAME::<input type="text" name="fname"><br/>
 ADRESS::<input type="text" name="adress"><br/>
 <input type="submit" value="STORE">
 </form>
</body>
</html>
Store.jsp
<html>
 <body>
 <%
 Cookie ckarr[]=request.getCookies();
 out.println("length;::"+ckarr.length);  //Here length is three the third one is default cookie is JSESSIONID COOCKIE. This jsessionId cookie
 //useful in session concept. You observe there.
   String defailtname=ckarr[0].getName();
   out.println("defailtname;::"+defailtname);
  
   
   String studentno=ckarr[1].getValue();
   String studentname=ckarr[2].getValue();
   String fathername=request.getParameter("fname");
   String address=request.getParameter("address");
    %>
     <%=studentno %><br/>
     <%=studentname %><br/>
     <%=fathername %><br/>
     <%=address %><br/>
  </body>
</html>
After cookies are created the programmer is responsible to write the code to send the cookies back to the client program. we can send the cookies back to the client program using response object.
Whatever cookies we want send it to client. They need to be added to  addCoockie() method of our response object.
Whenever client sends the request to the ftwo.jsp the server will create two cookies’ objects and they will send to the client program. response.addCoockie() method is responsible to send the cookie to the client program.

PROCESS OF HOW SERVER ADDS THE COOKIES TO THE BROWSER
http://localost:8080/ftwo.jsp:  When we send the above request query to the server. Request will go by request format. Then server will create the request object and also create the cookies (cookies are created in the form of an array). Then server will create the response object then cookies are added to response object. Then the response object gives it to ftwo.jsp. While giving response object to ftwo.jsp, server is responsible to translate HttpResponse object into HttpResponse format. When the server is translating the response object to response format, servers checks are there any cookies are available. If they are available the server converts the cookies into setcookie header format and sends it to the client program.
PROCESS OF WHEN WE SEND THE REQUEST FROM BROWSER THEN HOW COOCKIES ARD SENDS TO SERVER
Whenever the browser sends the request to server, The browser will check for the corresponding domain name. Are there any cookies are available. If it is available the cookies will be added to request object and send to server.
To read the cookies of the client program we use a method getCookies(). This method will return an array of cookies.
On the client program if the cookies are not available. Then request.getCookies() method will return null value. Because of the above reason if the programmer want to handle the cookies he need to check whether the cookies array is null or not. Otherwise it will give error.

TESTING OF COOKIES
See Above store.jsp. In that we display size of the cookie array. After sending the request to store.jsp you go to tools -> internet options and delete the cookies. Now again send the request to store.jsp. Now see the size of the cookies array...
PROGRAM
Like this you can iterate the arrays of cookies....
for(int i=0;i<ckarr.length;i++){
Cookie c=ckarr[i];
 String name=c.getName();
 if(name.equals(sno)){
 sno0=c.getValue();
     }
     if(name.equas("sno")){
     sno=c.getValue();
     }
}
THE MAIN APPLICATION AREA OF USING COOKIES
Generally cookies are not used as like above program for storing the data. It is not recommended to store data
The main purpose of using cookies is for developing personalized applications (Based on customer choice the application will display appropriate content)
1)  Two users are visiting the site. Internally have black background for the pages. But personally you want yellow background for page..I can develop an application using cookies generate the content according to the personal taste of user.
2)  If you open amazon.com and buy a books. And latter 5 days you buy toys form amazon.com after 5 days you open that site once again then it shows messages and images like new books are come, please buy it. And latter 5 days you open site once again. Now it shows a message new toys are come. Please buy it. It shows messages based on info of cookies.

SESSIONS
I have a doubt is this sessions concept and session scope concept is same or not i don't know. But i am thinking as these both are same. For every browser, on behalf of browser one session object is created. i think this session object only is used for  sessions, session scope concept..
From the Firefox browser when we send the request to fone.jsp. In the server it checks on behalf of Firefox browser the session object is available or not. As it not available the server will create the one session object on behalf of Firefox browser. Then the server will assign a unique id for the session object. Then server will create one cookies object with name JSESSIIONID, in that cookies, server stores the unique id of session object as value in the jsessionId cookies. And the cookies will send to Firefox browser with response object.
NOTE after session is created it will added to session object pool.
Second time when we send the request to any file in the domain (any jsp). Then the client program finds all the cookies which are belongs to that domain and send back all the cookies belong to that domain to the server. Now when server receives the request, the server first checks for a specific cookies JSESSIONID. If it is available then server gets the value from that and checks for already created session object unique id is available or not in that cookies on behalf of browser. If it is available it will not create the session object. Otherwise it will create the session object.
NOTE: If the client did not send any JSESSION cookies to the server, without checking in the object pool the server will create one session object on behalf of the client.
HOW TO REMOVE SESSION OBJECT FROM THE SERVER
After creating the session object in the server then you close the browser. Then cookies are removed from browser. So the mechanism of remembering client information will be removed. But the server will not be aware of restarting the browser and it holds old session object. Next time when we got the request the server treats that the client is sending the request for 1st time and create the session object.
According to the Servlet specification there are so many mechanisms are available to remove the session object from the server.
The programmer want to remove the session object we can use the method invalidate() to remove session object  from session object pool.
After session object is created inside the server it is not used for more than 30 minutes then server will remove the session object from the server( actually not remove - it made it as invalidate by invalidate()).
NOTE: Actually the program will not remove the session object. The object will be marked as invalidate object. Server will run the thread to remove all the invalid objects from session pool.
By default most of the server vendors will provide 30 minutes as default time out. But base on our project requirement we can reduce the time using    setMaxInactiveInterval(10)...This method takes no of seconds as input.
DISADVANTAGES OF SESSIONS: -
Sessions object consumes server resources. If too much of data is stored in the session object the performance of the applications will be affected. In case of sessions more amounts of data will not be transfer between client and server.
Hidden variables, cookies not use server resources. But sessions use server resources. Because we store data in session object. In the session we maintain data inside the server. But not in cookies, hidden variables, only session maintain data inside the server.
NOTE NOTE NOTE NOTE NOTE NOTE VVVVVVVVVVVVVVVVV VVVVVVVV IMP IMP IMP IMP IMP IMP IMP

COPY servlet-api.jar in delete folder and extract that servlet-api.jar in delete folder. Now in that one DTD file is there. In that DTD file all the tag names of web.xml file is there. If you want to use tags in web.xml file that tags must be specify in DTD FILE....
Instead of specifying the max time out in all jsps and servlets, we can specify the session time out in wex.xml file.
          In a project if we have 100 jsps and Servlets in all the files we need to specify maxInactiveTimeInterval(). If customer wants to change max time then you need to change in all jsps or Servlets. so better to declare in web.xml file...BY using tags <session-config>,<session-timeout>
To create the seseeion object we take help  of javax.servlet.http.HttpSession interface.
To create session in Servlets we use the following code.
 PROGRAM
 public void service(){
  printWriter out=response.getWriter();
  HttpSession session=null;
   sesssion==request.getSession();
   out.print("session id::"+session.getId());
}
When request.getseesion() is executed then service check weather already the session object available on behalf of this client. If it is not available getSession() creates a new session object. If it is available getSession() method returns the same session object which is already available.

request.getSession(true); If session object is already available it returns the session object. If it is not available it creates the new session object.
request.getSession(false);If session object is already available it returns the session object. If it is not available it returns the null value.
In case of jsp whenever we send the request to jsp. If session object is available it returns the session objects else it will create the new session object. Inside the generated Servlet for jsp it have the code something similar to    request.getSession(true); In the jsp it never returns null value. Because is has code something like request.getSession(true);
PROGRAM AND ONE PROBLEM WITH SESSIONS
trailOne.jsp
<html>
<body>
<form action="trailTwo.jsp">
 SANTOSH ONE : <input type="text" name="santoshOne"><br/>
 <input type="submit" value="NEXT">
 </form>
 </body>
</html>
trailTwo.jsp
<html>
<body>
 <form action="trailThree.jsp">
SANTOSH TWO : <input type="text" name="santoshTwo"><br/>
 SANTOSH THREE : <input type="text" name="santoshThree"><br/>
<input type="submit" value="NEXT">
</form>
</body>
</html>
trailThree.jsp
<jsp:useBean id="idOne"  class="com.siva.Trail" scope="session"/>
<jsp:setProperty property="santoshTwo" name="idOne"/>
<jsp:setProperty property="santoshThree" name="idOne"/>
<html>
<body>
<!--<jsp:getProperty property="santoshOne" name="idOne"/><br/>
<jsp:getProperty property="santoshTwo" name="idOne"/><br/>
<jsp:getProperty property="santoshThree" name="idOne"/><br/>
-->
 <c:out value="${sessionScope.idOne.santoshOne}" ></c:out><br/>
   <c:out value="${sessionScope.idOne.santoshTwo}"></c:out><br/>
value="${sessionScope.idOne.santoshThree}"></c:out><br/>
<c:out value="${sessionScope.idOne}"></c:out><br/>
<c:out value="${sessionScope}"></c:out><br/>
</body>
</html>
In the above code first you execute trailone,trailtwo,trailthree jsps. Now see the output. Then second time doesn’t close the browser and directly send the request to trailTwo.jsp. and fill the from then see the output. The changed values in trailTwo.jsp are displayed in output. But trailone.jsp values are displayed as it is. ie first form data is not changed. But second form data is changed..
NOTE: sessions are very good because they do not transfer the data between client and server. But much careful about the code.
In the session we maintain the data inside the server. But not transfer between client and server only by jsessionId coockie will maintain the state. But not with data
But in cookies and hidden variables data will not maintain in the server. But data is transfer between client and server. So session is the best technique compare to cookies and hidden variables. But careful while doing program with sessions.
Note:  There are two types of cookies are available. They are
1)) persistence Cookies
2)) Non persistence Cookies
Persistence cookies will store inside the hard disk of the computer. Non persistence cookies stored inside the memory of the program.
As persistence cookies store inside computer hard disk even we have restarted the application we can get back the cookies. Whereas nonresistance cookies store inside the program memory. If we restart the program we lose the cookies.
NOTE: BY default when we create the cookies’ they are of type nonresistance cookies.
To make a cookies’ as persistence cookies’ we need to set the expire date to the cookie. By default the cookie will become a non persistence cookie. The programmer is responsible to call the method setMaxAge() to make cookie as persistence cookie.
Inside the hard disk under the browsers cache folder the cookie will be stored. Writing state of the cookie in a file or hard disk is called as persistence.

URLREWRITING (NOT UNDERSTAND)

Q)) what is the purpose of urlreWriting?
In the browser if you set an option like server does not send cookies’ to client. You check this option in browser. Then server will not send the cookies’ to the client..
Now execute the above project with fone.jsp, ftwo.jsp, store.jsp. Then for every request separate session object is created i.e. in output diff session object id will shown to you..By this it not possible to maintain state full.
To achieve above problem we go to another technique is urlRewriting technique. For this for above program in every anchor tag we write like bellow.
<a href="<%=response.encodeUrl("one.jsp") %>"> By this with url every time id is add and send to server i.e. same session is send to server every time even we set an option in the browser for not accessing of cookies’.
 Sometimes the browser programs will not accept the cookies’. If the browser program has not accepted the cookies’ the session management will not work fine. To solve this problem we encode the url.
PROGRAM
<html>
 <%
<a href="<%=response.encodeUrl("two.jsp") %>"> two.jsp</a>
<a href="<%=response.encodeUrl("three.jsp") %>"> three.jsp</a>
%>
<html>
Whenever the encodeUrl() method is executed it takes the URL which we have specified and update with the sessionId of the object and send to the client.
SOME POINTS FROM SURESH FOR SESSION TRACKING
1. Hidden fields
2. Cookies
3. Session (session managed using Cookies)
4. Url rewriting (session managed using UrlRewritting)
Note: The 3rd and 4th concept is Sessions and urlrewriting technique both concepts depend on session object only. That‘s why session managed using cookies and session managed using urlrewritting.
Note: More amounts of data get transferred between the client and server in case of the application using hiddenfields(compare the application with single form with the application using multiple forms with hidden fields).
Note: In case of hidden fields, memory (server resources) will not be used on the server to remember the data provided by the user in the earlier steps.
Note: For cookies domain name (hot mail,gmail) is important, server port number is important, which web server(tomcat,weblogic) you are running not important to browser.
Note: Like hidden fields application more amount of data will be transfer between the client and server when the cookies are used. The application using cookies will fail, if the cookies are not accepted by the browser. We cannot use cookies when huge amount of data or information is given by the user in the forms. Like hidden fields, in case of cookies their server resources (memory) are not used.
Note: VVVVIMPVVVVVIMPVVVVVIMPVVVVIMP:
If the cookies are disabling in the browser, then the server will not be able to link up the session object with the browser.

Note: (But not understand) response.encodeUrl("three.jsp") generates the url with the is of the session object like three.jsp.
Note:  URL rewriting technique reduces the performance of the application. But our application will be able to use the session objects even if the cookies are not allowed by the browsers.

JUST INFORMATION
If an option set in the browser is not allow accessing the cookies i.e. block the cookies. Then for every request one session object is created. I.e. for form.jsp, gsf.jsp, sd.jsp.
     For the above three jsps for every request one session object is created. You send the request for form.jsp, for this one session object is created. Then request goes to gsf.jsp for this another session object is created. The values you fill in the form.jsp is stored in one session object. And the values you fill in the gsf.jsp is stored in another session object. So for every request one session object is created. Server memory is wasted and you get unreliable data i.e. wrong data.

CODE TO URL REWRITTING
In the above trailOne, trailTwo, trailThree jsps are there. Then in trailTwo.jsp in the form tag just you change the code for urlrewriting as bellow.
<form action="<%=response.encodeUrl("sd.jsp")%">

Note: The session object consumes server resources (memory). If too much of info (data) is stored in session object. Then the performance of the application will be affected.
Note: - In case of sessions more amounts of data will not be transferred between the client and server.

SMALL PROGRAM FOR HOW TO MAKE A COOCKIE AS PERSISTANCE
<%
cookie c1,c2;
c1 = new Cookie("ckone","value one");
c2 = new Cookie("cktwo","value two");
c2.setMaxAge(60*60*2*90); //just for example
response.addCookie(c1);
response.addCookie(c2);
%>

Our application has set cookies on browser. The cookie that will be lost when we close the browser is called as non Persistence cookie or session cookie .vone is the non persistence cookie. The browser stores this cookie in the memory.
The cookie that will stay with browser even if we close the browser is called as persistence cookie. The browser stores these cookies in the disk.
Note: - The old version of Firefox uses coockies.txt file and new version uses cookies. sqlite fie storing the cookies.
Internet explorer uses multiple files in temporary internet files folder for storing the cookies...


NOTE: VVVVIMP VVVVIMP VVVVIMP VVVVIMP
We can use the query string for passing on the information from jsp/manually developed Servlets to a jsp/manually developed Servlets

<a href="getmail.jsp?id=1">HELLO</a>
<a href="getmail.jsp?id=2">MAIL ONE</a>
<a href="getmail.jsp?id=3">MAIL TWO</a>

In above “getmail.jsp?id=1"    and id=2,id=3 are called query string.
Note: Query string is different for encodeUrl concept. In the jsp when you use enoceUrl() method then only it is a encode  Ur concept. But in spring how write the code for encode url, I don't know. I think query string is used in sendRedirect process.
The next concepts in suresh book is about is
1) Absolute path and relative path, context path and when you use absolute path and when you use relative path. I.e. used in RequestDispatcher object get from application (ServletContex) or request (ServletRequest). What happen when you get rd object from ServletContex, what happen when you get form ServletRequest. When you use absolute path and when you use relative path
2)  requestdispatcher.include(), requestdispatcher.forward(). Concepts
3) sendRedirect concept.
4)  what is the diff between the <%@ include="sitwo.jsp" %> and <jsp:include page="ditwo.jsp" />
NOTE:  We can use the path starting with a / excluding the context path as a parameter to
application.getRequestDispatcher();
request.getRequestDispatcher();
NOTE: - We can use the relative path with request.getRequestDispathcer() but not with application.getRequestDispathcer().


                           




 

No comments:

Post a Comment