JSP introductionTrainer = Subhasis NayakCMC
What is JSP ?It is a textual document that describes how to create a response object from a request object for given protocol.The processing of JSP page may involve:Creating objectsUsing objects.The default request & response objects areHttpServletRequestHttpServletResponse
What it provides?Capability to create both static & dynamic components.Dynamic capability that Servlet can provide.Integration of content.Manipulating data.
Information about JSPJava Server pages has these features:Language for developing java server pages.Constructs for accessing server-side objects.Defining extensions to the JSP language.It is a text based document that contains two types of text.Static template dataJSP elements which construct dynamic data.
JSP life cycleSome how similar to Servlet life cycle.When any request mapped to a JSP, it is handled by a special Servlet event.Servlet checks the java Server  Page’s Servlet is older than the java Server  Page.If so it translates to java Server  Page  into a Servlet class & compiles the class.Next the Servlet sends response to the java server page.
Advantages of JSPBuild process is performed automatically.Translation phase treat each data type in java Server Pages differently.Template data is transformed into code.This code emits that data stream that returns data to the client. It is faster than Servlet.
JSP Architecture ModelAccording to Sun  there 2 architectural model for building application using JSP & Servlet technology. Those are:JSP model 1JSP model 2
JSP model 1Not good for ComplexIn this model the every request to a JSP page. The requested page is completed  responsible for doing all the tasks required for fulfilling the request.Suite able for small application. In big application we put huge logic code to JSP.JSPBrowser1.requestEIS/DB2.CreateJava beans4.responseJava Beans3.Retrieve data
JSP model 2This architecture follows MVC design pattern.Servlet act as ControllerJSP act as ViewJava Bean act as ModelAll requests to Servlet. They analyze the request and collect data required to generate response into java beans objects. Then Servlet dispatch the request to JSP.JSP use data stored in java beans to generate a presentable response.
Cont’d …… Higher security
Easy maintainability Servlet(Controller)2.CreateJava beansEIS/DB3.Retrieve dataJava Beans(Model)Browser1.request4.Invoke JSP2.UseJava beans6.responseJSP(view)
JSP life Cycle.For 1st time when we accessed the JSP page server is slower after that it will faster.When we access JSP it is converted to it’s Servlet class before it can be used to service client side request.For each request the JSP engine checks the timestamps of source JSP page and corresponding Servlet if JSP is newer then it will be again converted to it’s equivalent Servlet. This process consists of 7-phases.
Cont’d …..
Elements of JSP
A simple JSP page<html> <body> <% out.println("<h1>Hello World!</h1>");%> </body> </html> Scriptlet
The processing of JSPWhen the browser asks the Web server for a JSP, the Web server passes control to a JSP container.A container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Because this is the first time this JSP has been invoked, the JSP container converts it into an executable unit called a Servlet.
Cont’d …… The entire page, including the parts that are in HTML, is translated into source code. After code translation, the JSP container compiles the Servlet, loads it automatically, and then executes it.Typically, the JSP container checks to see whether a Servlet for a JSP file already exists .If not it do the translation processIf version not match do the translation process
Let’s see the translated code of a JSPJSPServletDon’t worry about Servlet  file of JSP. JSP, why?<html> <body> <h1>Hello World!</h1> </body> </html>out.write("<html>\r\n"); out.write("<body>\r\n"); out.println("<h1>Hello World!</h1>"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n");
Let’s display SomethingOutput swill sameThe second one is the short hand code
Program displaying date
variablesYou can declare your own variables, as usualJSP provides several predefined variablesrequest :  The HttpServletRequest parameterresponse :  The HttpServletResponse parametersession :  The HttpSession associated with the request, or null if there is noneout :  A JspWriter (like a PrintWriter) used to send output to the clientExample:Your hostname: <%= request.getRemoteHost() %>
ScriptletsScriptlets are enclosed in <% ... %>tagsScriptletsdo not produce a value that is inserted directly into the HTML (as is done with <%= ... %>)Scriptlets are Java code that may write into the HTMLExample:<% String queryData = request.getQueryString();out.println("Attached GET data: " + queryData); %>Scriptlets are inserted into the Servletexactly as written, and are not compiled until the entire Servlet is compiledExample:<% if (Math.random() < 0.5) { %>Have a <B>nice</B> day!<% } else { %>          Have a <B>lousy</B> day!<% } %>
DeclarationsUse <%! ... %>for declarations to be added to your Servlet class, not to any particular methodCaution: Servlet are multithreaded, so nonlocal variables must be handled with extreme careIf declared with<% ... %>, variables are local and OKData can also safely be put in the request or session objectsExample:<%! private intaccessCount = 0; %>      Accesses to page since server reboot: <%= ++accessCount %>You can use<%! ... %>to declare methods as easily as to declare variables
DirectivesDirectives affect the Servlet class itselfA directive has the form: <%@ directiveattribute="value" %>or<%@ directiveattribute1="value1" attribute2="value2"                          ...attributeN="valueN" %>The most useful directive is page, which lets you import packagesExample:<%@ page import="java.util.*" %>
JSP CommentsDifferent from HTML comments.HTML comments are visible to client.<!-- an HTML comment -->JSP comments are used for documenting JSP code .JSP comments are not visible client-side.<%-- a JSP comment --%>
The include directiveThe include directive inserts another file into the file being parsedThe included file is treated as just more JSP, hence it can include static HTML, scripting elements, actions, and directivesSyntax:  <%@ include file="URL" %>The URL is treated as relative to the JSP pageThe include directive is especially useful for inserting things like navigation bars
ActionsActions are XML-syntax tags used to control the Servlet engine<jsp:include page="URL" />Inserts the indicated relative URL at execution time (not at compile time, like the include directive does)This is great for rapidly changing data<jsp:forward page="URL" /><jsp:forward page="<%= JavaExpression %>" />Jump to the (static) URL or the (dynamically computed) JavaExpression resulting in a URL
JSP in XMLJSP can be embedded in XML as well as in HTMLDue to XML’s syntax rules, the tags must be different (but they do the same things)HTML: <%= expression %>XML: <jsp:expression>expression</jsp:expression>HTML: <% code %>XML: <jsp:scriptlet>code</jsp:scriptlet>HTML: <%! declarations %>XML: <jsp:declaration>declarations</jsp:declaration>HTML: <%@ include file=URL %>XML: <jsp:directive.include file="URL"/>
Action – useBean tagThe useBean action tag is the most commonly used tag because of its powerful features.It allows a JSP to create an instance or receive an instance of a Java Bean.It is used for creating or instantiating a bean with a specific name and scope.Examples<jsp:useBean id=“time" scope="session" class="com.time.CurrentTimeBean" />
Session in jspIn session management whenever a request comes for any resource, a unique token is generated by the server and transmitted to the client by the response object and stored on the client machine as a cookie. Session management done by:Session ObjectCookiesHidden Form FieldsURL Rewriting
Program for math calculationDeclarative tagExpression tag
Program to display the string
XML style
Compare XML tag with normalNormal JSP tagXML tag of the JSP tag
Program to write scriptlet tagScriptlet tag
Lab questions?Declare an integer type variable and display it .Write the XMl style tag to declare and display the variable.Write a program to compare a string is equal to “welcome” .if equal display something else display something.Write a program to compare two strings values:1st string = “my fname”2nd sting = “my lname”If both strings are true then display “both are true” else display “one of them not true or no one is true”

C:\fakepath\jsp01

  • 1.
    JSP introductionTrainer =Subhasis NayakCMC
  • 2.
    What is JSP?It is a textual document that describes how to create a response object from a request object for given protocol.The processing of JSP page may involve:Creating objectsUsing objects.The default request & response objects areHttpServletRequestHttpServletResponse
  • 3.
    What it provides?Capabilityto create both static & dynamic components.Dynamic capability that Servlet can provide.Integration of content.Manipulating data.
  • 4.
    Information about JSPJavaServer pages has these features:Language for developing java server pages.Constructs for accessing server-side objects.Defining extensions to the JSP language.It is a text based document that contains two types of text.Static template dataJSP elements which construct dynamic data.
  • 5.
    JSP life cycleSomehow similar to Servlet life cycle.When any request mapped to a JSP, it is handled by a special Servlet event.Servlet checks the java Server Page’s Servlet is older than the java Server Page.If so it translates to java Server Page into a Servlet class & compiles the class.Next the Servlet sends response to the java server page.
  • 6.
    Advantages of JSPBuildprocess is performed automatically.Translation phase treat each data type in java Server Pages differently.Template data is transformed into code.This code emits that data stream that returns data to the client. It is faster than Servlet.
  • 7.
    JSP Architecture ModelAccordingto Sun there 2 architectural model for building application using JSP & Servlet technology. Those are:JSP model 1JSP model 2
  • 8.
    JSP model 1Notgood for ComplexIn this model the every request to a JSP page. The requested page is completed responsible for doing all the tasks required for fulfilling the request.Suite able for small application. In big application we put huge logic code to JSP.JSPBrowser1.requestEIS/DB2.CreateJava beans4.responseJava Beans3.Retrieve data
  • 9.
    JSP model 2Thisarchitecture follows MVC design pattern.Servlet act as ControllerJSP act as ViewJava Bean act as ModelAll requests to Servlet. They analyze the request and collect data required to generate response into java beans objects. Then Servlet dispatch the request to JSP.JSP use data stored in java beans to generate a presentable response.
  • 10.
  • 11.
    Easy maintainability Servlet(Controller)2.CreateJavabeansEIS/DB3.Retrieve dataJava Beans(Model)Browser1.request4.Invoke JSP2.UseJava beans6.responseJSP(view)
  • 12.
    JSP life Cycle.For1st time when we accessed the JSP page server is slower after that it will faster.When we access JSP it is converted to it’s Servlet class before it can be used to service client side request.For each request the JSP engine checks the timestamps of source JSP page and corresponding Servlet if JSP is newer then it will be again converted to it’s equivalent Servlet. This process consists of 7-phases.
  • 13.
  • 14.
  • 15.
    A simple JSPpage<html> <body> <% out.println("<h1>Hello World!</h1>");%> </body> </html> Scriptlet
  • 16.
    The processing ofJSPWhen the browser asks the Web server for a JSP, the Web server passes control to a JSP container.A container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Because this is the first time this JSP has been invoked, the JSP container converts it into an executable unit called a Servlet.
  • 17.
    Cont’d …… Theentire page, including the parts that are in HTML, is translated into source code. After code translation, the JSP container compiles the Servlet, loads it automatically, and then executes it.Typically, the JSP container checks to see whether a Servlet for a JSP file already exists .If not it do the translation processIf version not match do the translation process
  • 18.
    Let’s see thetranslated code of a JSPJSPServletDon’t worry about Servlet file of JSP. JSP, why?<html> <body> <h1>Hello World!</h1> </body> </html>out.write("<html>\r\n"); out.write("<body>\r\n"); out.println("<h1>Hello World!</h1>"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n");
  • 19.
    Let’s display SomethingOutputswill sameThe second one is the short hand code
  • 20.
  • 21.
    variablesYou can declareyour own variables, as usualJSP provides several predefined variablesrequest : The HttpServletRequest parameterresponse : The HttpServletResponse parametersession : The HttpSession associated with the request, or null if there is noneout : A JspWriter (like a PrintWriter) used to send output to the clientExample:Your hostname: <%= request.getRemoteHost() %>
  • 22.
    ScriptletsScriptlets are enclosedin <% ... %>tagsScriptletsdo not produce a value that is inserted directly into the HTML (as is done with <%= ... %>)Scriptlets are Java code that may write into the HTMLExample:<% String queryData = request.getQueryString();out.println("Attached GET data: " + queryData); %>Scriptlets are inserted into the Servletexactly as written, and are not compiled until the entire Servlet is compiledExample:<% if (Math.random() < 0.5) { %>Have a <B>nice</B> day!<% } else { %> Have a <B>lousy</B> day!<% } %>
  • 23.
    DeclarationsUse <%! ...%>for declarations to be added to your Servlet class, not to any particular methodCaution: Servlet are multithreaded, so nonlocal variables must be handled with extreme careIf declared with<% ... %>, variables are local and OKData can also safely be put in the request or session objectsExample:<%! private intaccessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %>You can use<%! ... %>to declare methods as easily as to declare variables
  • 24.
    DirectivesDirectives affect theServlet class itselfA directive has the form: <%@ directiveattribute="value" %>or<%@ directiveattribute1="value1" attribute2="value2" ...attributeN="valueN" %>The most useful directive is page, which lets you import packagesExample:<%@ page import="java.util.*" %>
  • 25.
    JSP CommentsDifferent fromHTML comments.HTML comments are visible to client.<!-- an HTML comment -->JSP comments are used for documenting JSP code .JSP comments are not visible client-side.<%-- a JSP comment --%>
  • 26.
    The include directiveTheinclude directive inserts another file into the file being parsedThe included file is treated as just more JSP, hence it can include static HTML, scripting elements, actions, and directivesSyntax: <%@ include file="URL" %>The URL is treated as relative to the JSP pageThe include directive is especially useful for inserting things like navigation bars
  • 27.
    ActionsActions are XML-syntaxtags used to control the Servlet engine<jsp:include page="URL" />Inserts the indicated relative URL at execution time (not at compile time, like the include directive does)This is great for rapidly changing data<jsp:forward page="URL" /><jsp:forward page="<%= JavaExpression %>" />Jump to the (static) URL or the (dynamically computed) JavaExpression resulting in a URL
  • 28.
    JSP in XMLJSPcan be embedded in XML as well as in HTMLDue to XML’s syntax rules, the tags must be different (but they do the same things)HTML: <%= expression %>XML: <jsp:expression>expression</jsp:expression>HTML: <% code %>XML: <jsp:scriptlet>code</jsp:scriptlet>HTML: <%! declarations %>XML: <jsp:declaration>declarations</jsp:declaration>HTML: <%@ include file=URL %>XML: <jsp:directive.include file="URL"/>
  • 29.
    Action – useBeantagThe useBean action tag is the most commonly used tag because of its powerful features.It allows a JSP to create an instance or receive an instance of a Java Bean.It is used for creating or instantiating a bean with a specific name and scope.Examples<jsp:useBean id=“time" scope="session" class="com.time.CurrentTimeBean" />
  • 30.
    Session in jspInsession management whenever a request comes for any resource, a unique token is generated by the server and transmitted to the client by the response object and stored on the client machine as a cookie. Session management done by:Session ObjectCookiesHidden Form FieldsURL Rewriting
  • 31.
    Program for mathcalculationDeclarative tagExpression tag
  • 32.
  • 33.
  • 34.
    Compare XML tagwith normalNormal JSP tagXML tag of the JSP tag
  • 35.
    Program to writescriptlet tagScriptlet tag
  • 36.
    Lab questions?Declare aninteger type variable and display it .Write the XMl style tag to declare and display the variable.Write a program to compare a string is equal to “welcome” .if equal display something else display something.Write a program to compare two strings values:1st string = “my fname”2nd sting = “my lname”If both strings are true then display “both are true” else display “one of them not true or no one is true”