jsp

250
Session Tracking

Upload: siwa-karthikeya-ambati

Post on 26-Sep-2015

214 views

Category:

Documents


1 download

DESCRIPTION

java servlet pages

TRANSCRIPT

PowerPoint Presentation

Session TrackingMechanism of Http ProtocolThe communication between web browser and web server by http protocol will be done like the followingWhen a client request is made then http protocol opens a socket connection with a server internallyHttp protocol transfer values from browser side to server sideAfter processing is done at server side, the values are transferred from server to browserHttp protocol closes the socket connectionThe above 4-steps are repeated fro each request made from a browserStateless behaviorWhen a client request is made to a server then server reads client data and process the request, after that the response will be send back to the clientOnce response is given back to the client, a server doesnt remember any data of the client. So when same client is sending another request to server then server doesnt recognize that clientThis behavior is called as stateless behaviorIn a stateless behavior, a server feels that each request made by a new client

Stateful behavior When a client request is made to a server then a server store data of the client and whenever the same client is visiting again to the server then server recognize a clientThis behavior is called as stateful behaviorSession TrackingHttp protocol by default behaves like a stateless protocol. But in some applications, we need statteful behavior. To convert the http protocol behavior from stateless to stateful we apply a mechanism called session tracking.Session tracking is a combination of session management and state managementSession management is nothing but identifies a client whether is a old or a new and state management is nothing but remember the values of client at server sideHow Session Management works?When a client request is made to a server then server first checks whether a client is an old client or a new client by identifying a tokenIf there is no token in the client request then server identifies the client as new and generates a new token and after that the token will be sent to the client along with a responseWhen the same client is next time visiting server then along with the request the token will also be sent to the server.So a server identifies the client as an existing client

Session Management

request-1response+tokenRequest(2)+tokenresponseClient-1ServertokenHow State Management WorksState management refers to remembering a client data in a serverIn order to remember a client data in a server, at server an object will be created for each new clientIf a server remember a client data then a response for a request of a client, can be constructed by depending on not only the current values but also depending on previous values of the clientIn order to remember a client data in a server, for each new client one object will be created and the data will be stored in that object until the client logout from the serverWhenever a client request is made to server for first time then at server side a token and an object both are generated for a client. Here token for session management and object for state managementThe number of clients connected with a server is equal to the number of tokens generated by the server and it is equal to number of objects created for storing the data

State Management

client-1session objectto store client-1dataclient-2session objectto store client-2dataSession Tracking TechniquesThe following four techniques are used to fulfill session tracking mechanismHttpSession InterfaceHidden Form FieldsCookiesURL RewritingHttpSession InterfaceHttpSession InterfaceIn servlet api, HttpSession interface contains a method called getSession() and this method contains the logic of creating session-id and session-objectWe have getSession() method in two flavoursgetSession()getSession(boolean)When we call getSession() it returns an associated session-object of a clientgetSession() contains logic of verifying whether a client who send the request is containing a session-id or not and also contains logic for creating new session-id and session-objectWhen we call getSession() then it internally calls getSession(true)

HttpSession InterfaceThe logic of getSession(true) is, it checks whether the given request is associated with a session-id or not. If yes then identifies the client as an existing client and returns the associated session-objectHttpSession session=request.getSession();HttpSession session=request.getSession(true);getSession(false) verifies whether a client who send this request is associated with a session-id or not, if contains then, it returns the associated session-object, if not contains then returns null.It means, getSession(false) method doesnt generate any new session-id and session-objectHttpSession session=request.getSession(false);HttpSession InterfaceIn HttpSession interface technique, a session-id is transfer between a client and server in the form of cookieWhen a response is send to a client then along with response a cookie will be added for the response, which contains session-id and this cookie will be transfer from a server to a clientWhen a client is sending next request to a server then along with request the cookie which contains session-id will also be transfer to the server with the help of this cookie a server will identify a client

Storing and sending data in Session objectIf you want store or read the data in session-object then it will in the form of attributes, it means a session object stores data in key-value pairIn order to store or read data of a session-object then we need to use the following four methodssetAttribute(key, value)getAttribute(key);removeAttribute();getAttributeNames();The above methods are some times called as state management methods of HttpSessionMethods of HttpSession interfacegetId()This method returns a session-id associated with a session-objectString str=session.getId();isNew()This method is to know the state of a session object that is, whether a session is new or oldIf the session is new then a client is a new client and if the session is old then the client is old clientif(session.isNew()){//logic-1}else{logic-2}Methods of HttpSession interfacegetMaxInactiveInterval()This method return maximum waiting time allowed between a request and next requestIf the time gap exceeds the maximum inactive interval then the server will automatically discord/remove/destroy a client sessionThe inactive interval time varies from one server to another server.This method returns inactive interval time in secondslong seconds=session.getMaxInactiveInterval();Methods of HttpSession interfacesetMaxInactiveInterval()This method is used to set a session expire time explicitlyBy default, each session generated by the container will have some expire timeAs a programmer, we can set/change the expire time for a session in following 2-waysProgrammaticallyDeclarativelyIf we want to set programmatically then we need to call setMaxInactiveInterval() method by passing input value in secondssession.setMaxInactiveInterval(10);

We can also set a session expire time declaratively through web.xml file like,

15

If we set expire time for a session in both programmatic and declarative approaches then programmatic value will be considered

Difference between Programmatic and Declarative approachesIn programmatic approach we can set minimum expire time for a session as one second. In declarative approach we can set a minimum expire time for a session as one minuteIn programmatic approach we can set a session expire time in each servlet differently. But in declarative approach, the expire time will be commonly applied for all servlets

In programmatic or declarative approach, if we set a session expire time as ve value then that session doesnt expire until it is explicitly invalidatedIn order to expire a session explicitly then we need to call invalidate() methodWhen we sign-out/logout from website then internally invalidate() method is called to expire a session of a clientHttpSession interface methodsgetCreationTime()This method is used to get a session creation time.This method returns millisecondsThese milliseconds are calculated from 1970,Jan-1,00:00 hoursWe can convert these milliseconds into system date and time format by using java.util.Data classlong ms=session.getCreationTime();java.util.Date d=new java.util.Date(ms);out.println(d.toString());HttpSession interface methodsgetLastAccessedTime()This method is used to read last request/accessed time by a client with a session. It returns millisecondsThese milliseconds are calculated from 1970,Jan-1,00:00 hoursFor first request and second request both creation time and last accessed time both are one and sameFrom third request by a client, creation time and last accessed time will be differentlong ms=session.getLastaccessedTime();java.util.Date d=new java.util.Date(ms);out.println(d.toString());

Cookie ClassCookie ClassCookie class is given in javax.servlet.http packageGenerally, a cookie is defined as an object which contains/stores text information in the form of key-value pair, created on server and stored on browserIn servlet api, we create cookie class objects for client data and these cookies are transferred from server to browser and browser to along with that clientCookies are only for state management and but not for session management. So cookies are for particial session tracking in web applications With the help of cookies, it is possible to transfer previous data of client also along with current data from a browser to a server. So that server can access both current data and also previous data of clientCookie ClassWhile working with cookies the programmer is responsible to create the cookies and the programmer is responsible to send cookies to browser and also to read cookies from browserThe cookies which are created by the programmer are called data cookies. In order to create data cookie, we need Cookie class of servlet apiWhile working with HttpSession technique, internally session-id will be transferred between a server and a client in the form of a cookie. But this cookie is a container generated cookie and the container is responsible to transfer this cookie on to the browserWhile creating cookie, we are responsible to pass name and value into a cookie object

Cookie classSyntax: Cookie c1=new Cookie(String name, String value);If any cookies are created explicitly then the servlet programmer is responsible to transfer the cookies from a server to browser explicitly.To transfer a cookie from a server to browser it must added to the response object by calling addCookie() methodResponse.addCookie(c1);When a request is given from a browser, then a browser automatically transfers cookies also to the server. In a servelet, to read these cookies, we need to call getCookies() method of HttpServeltRequest interfaceCookie coo[]=request.getCookies();Types of CookiesIn-Memory CookiePersistance Cookie

In-memory CookieBy default whenever a new cookie is created then it is an in-memory cookieAn in-memory cookie will be alive on browser until that browser is closedThe in-memory cookie contains its expire time as -1

Types of CookiesPersistance CookieFor a cookie, if we set some expire time then that cookie becomes as a persistance cookieA persistance cookie will be alive on browser until its expire time is reachedA persistance cookie will not removed from a browser even though the browser is closed

Methods of Cookie classsetValue()This method is used to modifies the values stored in cookie objectOnce a cookie object is created, then its name cant be modified(key) but its value can be modifiedCookie c1=new Cookie(user,talent);Key is user and Value is talentc1.setValue(Java);Now Key is user and Value is Java

Methods of Cookie classgetName() and getValue() These methods are used to read key and value stored in a cookie object

Cookie c1=new Cookie(ram, java);String s1=c1.getName();System.out.println(s1); //ramString s2=c1.getValue();System.out.println(s2);

Methods of Cookie ClasssetMaxAge() and getMaxAge() These methods are used to set expire time and used to read expire time respectivelyIf we want to change a cookie in-memory to persiatance then we need call setMaxAge() methodBy reading expire time of a cookie, we can identifies whether it is in-memory or a persistance cookieCookie c1=new Cookie(ram,java);c1.setMaxage(120); //secondslong k=c1.getMaxAge();if(k==-1) in-memory cookieelsepersistance cookieMethods of Cookie classsetComment() and getComment()These methods are used to set a comment for a cookie and also to read a comment of a cookie respectivelyCookie c1=new Cookie(ram,java);C1.setComment(This is Ram Cookie);String s1=c1.getComment();System.out.println(s1); //This is Ram CookieJSPLimitations of ServletsServlet need huge amount of java code to implement business logicIn a servlet both business logic and presentation logic combined. So a java developer must be know html alsoA servlet is a java class file, so if any modifications are done on it then we must recompile, reload the application and sometimes we need to restart the serverIn servlets, we dont have implicit objects supportWhat is JSP?A JSP is a web page, resides on a server and provides dynamic presentation on browserA JSP is page, looks like on HTML page, the difference is HTML can produce only static content, but a JSP can produce dynamic contentJSPs are called pages rather than programs because a JSP contains every thing in the form of a tagJSPs are pages, written by authors

Difference between a Servlet and JSPServletsJspServlet need huge amount of java code to implement business logicA Jsp need less amount of java code to implement business logicIn a servlet both business logic and presentation logic combined. So a java developer must be know html alsoIn Jsp, we can separate presentation logic from business logic. So, a programmer may not be html designerA servlet is a java class file, so if any modifications are done on it then we must recompile, reload the application and sometimes we need to restart the serverIn Jsp, it is a page so if any modification are done then no need to recompile or reload or restart the server. Instead, we need to refresh to page on broserIn servlets, we dont have implicit objects supportIn a Jsp, we have implicit objectsA servlet doesnt manage a session by default. Explicitly we need to enable sessionsA Jsp by default maintains sessions. If we dont require them then we can disable themIn a servlet, we have to write all import statements on top of the servletIn Jsp, we can insert import statements at any where in the pageContents of JSP PageOrdinary text (template text)Html tagsJsp tagsOrdinary text and Html tags will produce static content and Jsp tags will generate dynamic contentA Jsp is a server side resource. It means a jsp executes at server side and its response will be constructed in the form of web page and that web page is delivered to web clientHtml tags are enclosed with in < >Jsp tags are enclosed with in Jsp ExecutionAt server side, 2-phases are executed for a JspTranslation PhaseRequest Processing PhaseTranslation phase means, translating a jsp into equivalent servlet and then generating a .class fileRequest processing phase means, executing service() method for a given request and generating response to the clientTranslation doesnt occur for each request. But request processing occurs for each requestTranslation occurs in the following 2-casesWhen a first request is arrived to a jspWhen request arrived after modification of a jsp

First RequestFirst Request Received by Jsp

http://localhost:8080/app1/one.jspone.jspone_jsp.javaone_jsp.classobject_jspService(-,-){ ----- -----}requesttranslatorcompilerresponseNext Request on wards http://localhost:8080/app1/one.jspone.jspobject_jspService(-,-){ ----- -----}requestresponseJsp pages are not compiled by the developers explicitly. But t server side, a web container will do jsp compilation. It means a jsp also need compilation, because a jsp is internally converted to a servletA web container uses a page compiler(translator), to convert a .jsp file into .java fileFor example, catelina is a web container of tomact, uses a page compiler called jasper, to translate a .jsp into a .java fileAfter converted to .java file, container uses javac and generate .class fileTo identify whether a jsp is like a previous executed jsp or any modifications done on it, a web container uses file comparison tools. In tomact catalina uses araxis tool for identificationA jsp is executed in a server, if we shutdown a server then the object created for a jsp will be removed from the server. But the .java and .class files are not removedIf we restart the server and if you again give a request to a jsp then the container creates an object for existing class and invokes its life cycle and then provides the response back to the clientIf you shutdown and restart the server then again translation phase for a jsp will not be executedIf we remove .class file and if you give request to a jsp then partial translation occurs and again a new .class file created and the request processing will be executedWe can modify the source code of an internal servlet created by the container for a jsp. In this case to execute the modified code also, either we need to explicitly compiled or we need to remove .class fileJsp Life CycleJsp is translated to a servletThe servlet is compiledThe servlet is loaded into memoryAn object is created for the servletjspInit() method is called_jspService(-,-) method is calledjspDestroy() method is called(above steps are divided into 4-phases )When a jsp is converted to a servlet, the servlet class extends a base class provided by the container. That class extends from HttpServlet class. So we can say that the internal servlet is an HttpServletA jsp can handle only http protocol request

JSPlife cycle can be divided into four phases:Translation, Initialization, execution and finalization.TranslationIn the translation phase, JSP engine checks for the JSPsyntax and translate JSP page into its page implementation class if the syntax is correct. This class is actually a standard Java servlet. After that, JSPengine compiles the source file into class file and ready for use.If the container receives the request, it checks for the changes of the JSPpagesince it was last translated. If no changes was made, It just loads the servlet otherwise the process of check, translate and compile occurs again. Because the compilation process takes time so JSPengine wants to minimize it to increase the performance of the page processing.

InitializationAfter the translation phase, JSPengine loads the class file and create an instance of the servlet to handle processing of the initial request. JSPengines will call a method jspInit() to initialize the a servlet. jspInit method is generated during the translation phase which is normally used for initializing application-level parameters and resources. You can also overide this method by using declaration.

ExecutionAfter the initialization phase, the web container calls the method _jspService() to handle the request and returning a response to the client. Each request is handled is aseparated thread. Be noted that all the scriptlets and expressions end up inside this method. The JSPdirectives and declaration are applied to the entire page so the are outside of this method.

FinalizationIn the finalization phase, the web container calls the method jspDestroy(). This method is used to clean up memory and resources. Like jspInit() method, you can override the jspDestroy() method also to do your all clean up such as release the resources you loaded in the initialization phase....

Jsp Life CycleThe life cycle methods of jsp are provided by HttpJspPage interface. This interface is part of JSP api and it is given in javax.servlet.jsp.*; packageHttpJspPage is exentended from JspPage interface and it has provide two life cycle methods called jspInit() and jspDestroy()Jsp Tags (Elements)Jsp tags are divided into the following1)Scripting Tags declaration, expression, scriptlets2)Directivies Include, page, taglib3)Stand Actions 4)Custom Tags

JSP Scripting ElementsJSP scripting elements enable us to insert java code into JSP files.

There are three types of elementsExpressionsScriptletsDeclarationsSeptember 9, 201454JSP declaration tagThis tag is used for define variables and creating methods in a jsp pageIf we define any variable or methods then these variables and methods will become instance variables and instance methods of the internal servlet classThis tag starts with Syntax: (html format)

Syntax: (xml format)

Instance or global variables define method

The variables defined in this tag will become global to the entire jsp. It means we can use those variables at every where in the jspThe declaration tag will be executed for only once but not for each requestThe code inserted into declaration will be placed into servlet class during translation time

JSP declaration tag

First request count=1Second request count=1Third request count=1....nth request count=1(declaration1.jsp)JSP declaration tagIn declaration tag we can override jspInit(0 and jspDestroy() methods. _jspService(-,-) override is not possible. _jspService(-,-) always written by the container

JSP declaration tagIn a jsp, the only one tag which allows jsp programmers to define methods is declaration tagIf we define a method in a declaration tag then it can be called from any number of times from an expression tag and scriplet tag of jsp(declaration2.jsp)We cant use implicit objects of a jsp in declaration tag. Because the declaration tag code goes out of _jspService(-,-) method

JSP declaration tagFor scripting elements of a jsp, nesting of tags ate not allowed

The code is an error because nesting is not allowed

It is an error because insert one scriptnig element into another scripting element is wrong

Examples on declaration tagdeclaration1.jsp

Examples on declaration tagdeclaration2.jsp

JSP ExpressionsAn expression tag is used for evaluating the given expression and then printing or displaying result on to the browserEach expression tag will be internally converted to out.println() method statements during translation time and then that statements will be inserted into _jspService() methodExpression tag will be executed for each request, because an expression tag goes inside of _jspService() methodWe can use implicit objects of jsp in an expression tag. Because its code goes into _jspService(0 methodA JSP expression is used to insert java code directly into the output.

September 9, 201462JSP ExpressionSyntax (html syntax)

expression (xml syntax)

Eg:Current Time:

Output:Current Time: Tue Aug 22 21:05:47 IST 2006

The expression is evaluated, converted to string and inserted into the page.

Jsp ExpressionsExample out.print(a+b,a-b) //invalid out.print(a+b+ +a-b)//valid out.print(this.a*this.b); out.print(this.a+page.a);page.a equls this.aout.print(a+b;); //invalidout.print(a,b);//invalid

out.println(request.getParameter(uname));

Jsp Expressions example

Single quote`Date Formatting using printf:

Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table given below.

Date and Time Conversion CharactersCharacterDescriptionExamplecComplete date and timeMon May 04 09:51:52 CDT 2009FISO 8601 date2004-02-09DU.S. formatted date (month/day/year)02/09/2004T24-hour time18:05:19r12-hour time06:05:19 pmR24-hour time, no seconds18:05YFour-digit year (with leading zeroes)2004yLast two digits of the year (with leading zeroes)04CFirst two digits of the year (with leading zeroes)20BFull month nameFebruarybAbbreviated month nameFebmTwo-digit month (with leading zeroes)02dTwo-digit day (with leading zeroes)03eTwo-digit day (without leading zeroes)9AFull weekday nameMondayDate and Time Conversion CharactersaAbbreviated weekday nameMonjThree-digit day of year (with leading zeroes)069HTwo-digit hour (with leading zeroes), between 00 and 2318kTwo-digit hour (without leading zeroes), between 0 and 2318ITwo-digit hour (with leading zeroes), between 01 and 1206lTwo-digit hour (without leading zeroes), between 1 and 126MTwo-digit minutes (with leading zeroes)05STwo-digit seconds (with leading zeroes)19LThree-digit milliseconds (with leading zeroes)047NNine-digit nanoseconds (with leading zeroes)047000000PUppercase morning or afternoon markerPMpLowercase morning or afternoon markerpmzRFC 822 numeric offset from GMT-0800ZTime zonePSTsSeconds since 1970-01-01 00:00:00 GMT1078884319QMilliseconds since 1970-01-01 00:00:00 GMT1078884319047Sleep Time Exampleimport java.util.*; public class SleepTime { public static void main(String args[]) { try { System.out.println(new Date( ) + "\n"); Thread.sleep(5000); System.out.println(new Date( ) + "\n"); } catch (Exception e) { System.out.println("Got an exception!"); } }}Calendar ClassJava's java.util.Calendar class is used to do date and time arithmetic. Whenever you have something slightly more advanced than just representing a date and time, this is the class to use.The java.util.Calendar class is abstract, meaning you cannot instantiate it. The reason is that there are more than one calendar in the world. For instance, the Arab calendar uses a different year as year 0 than the Gregorian calendar used by most western countries.

Instantiating a GregorianCalendarJava only comes with a Gregorian calendar implementation, the java.util.GregorianCalendar class. Here is how you instantiate a GregorianCalendar:Calendar calendar = new GregorianCalendar(); A new GregorianCalendar has the date and time set to "now", meaning the date and time it was created

Example