Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to JSP Java Server Pages

Similar presentations


Presentation on theme: "Introduction to JSP Java Server Pages"— Presentation transcript:

1 Introduction to JSP Java Server Pages
Ziad A. Al-Sharif

2 Overview JSP technology has facilitated the segregation of the work of a Web designer and a Web developer. A Web designer can use HTML to design and formulate the layout for the Web page A Web developer can work independently and use java code and JSP specific tags to implement the business logic The simultaneous construction of the static and dynamic content facilitates development of quality applications with increased productivity.

3 What is JSP Scripting elements are used to provide dynamic pages
JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to “.jsp” instead of ".html". On the other hand, Servlets are pure Java programs. They introduce dynamism into web pages by using programmatic content. In this section we will introduce the JSP technology, afterward, we will consider the servlet technology. JSP are text based documents Two major components of JSP: Static content: provided by HTML or XML Dynamic content: generated by JSP tags and scriplets written in Java language to encapsulate the application logic.

4 JSP and Servlets JSP technology is an extension/wrapper over the Java servlet technology. A JSP page , after compilation, generates a servlet and therefore incorporates all servlet functionalities. Servlets and JSP thus share common features, such as: platform independence (java based) creation of database-driven Web applications and server side programming capabilities. However, there are also some basic differences between servlets and JSPs :

5 Overview: JSP vs. Servlets
Servlets tie up files to independently handle the static presentation logic and the dynamic business logic. an HTML file for the static content and a Java file for the dynamic contents a change made to any file requires recompilation of the servlet JSP on the other hand allows Java to be embedded directly into an HTML page by using tags The HTML content and the Java content can also be placed in separate files. Any changes made to HTML content is automatically compiled and loaded onto the servlet

6 Overview: JSP vs. Servlets
Servlet programming involves extensive coding. Therefore, any change made to the code requires identification of the static code content (for the designer) and dynamic code content (for the developer) to facilitate incorporation of the changes. A JSP page, by virtue of the separate placement of the static and dynamic content: facilitates both Web developers and the Web designer to work independently.

7 JSP Life Cycle When the client (web browser) requests a particular JSP page the server in turns sends a request to the JSP engine. The JSP engine is part of a Web container, that compiles a JSP page to a servlet. Each JSP page is turned into a Java servlet, compiled and loaded. This compilation happens on the first request. After the first request, the file doesn’t take long to load anymore. Every time you change the JSP file, it will be re-compiled again. The following figure represents the process of the flow of events that occur after a client requests for a JSP page.

8 Servlet generation and recompilation
Request-Response Cycle for a JSP Page Browser Web Container ( JSP Engine ) Yes No Response Check to ensure if the call to JSP is first of its kind Servlet generation and recompilation Servlet reloaded Request

9 Request-Response Cycle for a JSP Page
The request-response cycle essentially comprises of two phases: the translation phase and the request-processing phase. The translation phase is implemented by the JSP engine and involves generation of a servlet. Internally , this results in the creation of a class file for the JSP page, that implements the servlet interface. During the request-processing phase: the response is generated according to the request specifications. After the servlet is loaded for the first time: it remains active processes all the subsequent requests , and saves time that would otherwise be lost in reloading a servlet at each time.

10 JSP compilation into Servlets
Initial request Web Browser Web Server J2EE Web Container translation Java Servlets Subsequent request

11 Request-Response Cycle for a JSP Page

12 JSP Methods Once a JSP is translated to a servlet , the container invokes the following life cycle methods on the servlet , that are defined in the javax.servlet.jsp.JspPage interface: jspInit() : This method is invoked at the time when the servlet is initialized. jspService() : This method is invoked when request for the JSP page is received. jspDestroy() : This method is invoked before the servlet is removed from the service.

13 JSP Scripting elements

14 JSP Scripting elements
The scripting elements provides the ability to insert java code inside the JSP There are three types of scripting elements: Declaration tag Expression tag Directive tag Scriptlet tag Action tag

15 1. Declaration tag (<%! %>)
This tag allows the developer to declare variables or methods. Before the declaration you must have <%! And at the end of the declaration the developer must have %> Code placed in this must end in a semicolon(;). Declarations do not generate output, so are used with JSP expressions or scriptlets

16 Example 1: JSP Declaration Tag
test1.jsp <html>   <body>   <%! int data=50; %>   <%= "Value of the variable is:"+ data %>   </body>   </html>  test2.jsp <html>   <body>   <%!    int cube(int n){   return n*n*n*;   }   %>   <%= "Cube of 3 is:“ +cube(3)  %>   </body>   </html>  

17 2. Expression tag (<%= %>)
This tag allows the developer to embed any java expression within the HTML code It is mostly using the out.println() A semicolon (;) does not appear at the end of the code inside the tag

18 Example 1: JSP expression tag
test1.jsp <html>   <body>   <%= "welcome to jsp" %>   </body>   </html>   test2.jsp <html>   <body>   Current Time: <%=  java.util.Calendar.getInstance().getTime()  %>   Current Date and Time is : <%= new java.util.Date() %> </body>   </html>

19 Example 2: JSP expression tag
index.jsp <html>   <body>   <form  action=“welcome.jsp“ >   <input type =“text"  name="uname“ >   <input type =“submit"  value="go"> <br>   </form>   </body>   </html>   welcome.jsp <html>   <body>   <%= “Welcome “ + request.getParameter("uname") %>   </body>   </html> 

20 3. Directive tag (<%@ directive…. %>)
A JSP directive gives special information about the jsp page , to the JSP Engine. There are three main types of directives: page processing information for this page Include files to be included Tag library tag library to be used in this page Directives do not produce any visible output when the page is requested but change the way the JSP engine processes the page For example , you can make session data unavailable to a page by setting a page directive (session) to false. more to come here???

21 Examples: JSP Directive
Import java packages page import="java.util.*, java.sql.*" %> Multiple import statements page import="java.util.*" %> page import="java.sql.*" %> Including file at translation time include file="header.html" %> For include the path is relative to the JSP file

22 4. Scriptlet Tag (<%... %>)
Between <% and %> tags , any valid Java Code is called a Scriptlet. This code can access any variable or bean declared. index.jsp <html>   <body>   <% String message = “Hello World !” ; out.println(message); %> </body>   </html>  

23 Example 1: JSP Scriptlet Tag
index.html <html>  <body>   <form  action="welcome.jsp“ >   <input type ="text" name="uname“ >   <input type ="submit"  value="go"> <br>   </form>   </body>  </html>   welcome.jsp <html>  <body>   <%   String name = request.getParameter("uname");   out.print("welcome :“ + name );   %>   </body>  </html> 

24 5. Action Tag Standard actions
There are three main roles of the action tags: Enable the use of the server side Javabeans Transfer control between pages browser independent support for applets Standard actions Example: <jsp:useBean> ... </jsp:useBean>

25 JSP comments <%-- JSP comment--%>
JSP comments are similar to HTML comments <!– HTML comment -- > except JSP comments are never sent to the user’s browser. HTML comments are visible in the page source Index.jsp <html> <head> <title> HTML and JSP Comments </title> </head> <body>   <h2> Comments </h2> <!— This HTML Comment-visible in the page source --> <%-- This JSP comment-Not visible in the page source -- %> </body>   </html> 

26 JSP Implicit Objects

27 JSP Implicit Objects There are 9 JSP implicit objects. These objects are created by the web container that are available to all the JSP pages. Object/Variable Type out javax.servlet.jsp.JspWriter request javax.servlet.http.HttpServletRequest response javax.servlet.http.HttpServletResponse config javax.servlet.http.ServletConfig application javax.servlet.http.ServletContext session javax.servlet.http.HttpSession pageContext javax.servlet.jsp.PageContext page javax.lang.Object exception javax.lang.Throwable

28 1-JSP implicit object: out
JSP provides the out implicit object of type JspWriter. index.jsp <html>   <body>   <%  out.print(2*5);  %>   </body>   </html>   index.jsp <html>   <body>   <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>   </body>   </html>  

29 2-JSP implicit object: request object
The JSP request is an implicit object of type HttpServletRequest It access to information associated with a request. normally used in looking up parameter values and cookies. It is created for each jsp request by the web container It can be used to get request information such as: parameter, header information, remote address, server name, server port, content type, character encoding etc. index.html <html>  <body>   <form  action="welcome.jsp“ >   <input type ="text" name="uname“ >   <input type ="submit"  value="go"> <br>   </form>   </body>  </html>   welcome.jsp <html>  <body>   <%   String name = request.getParameter("uname");  out.print("welcome :“ + name );   %>   </body>  </html> 

30 3-JSP implicit object: response object
In JSP, response is an implicit object of type HttpServletResponse. It is created by the web container for each jsp request. It can be used to add or manipulate response such as: redirect response to another resource send error etc. index.html <html>   <body>   <form  action="welcome.jsp“ >   <input type ="text" name="uname“ >   <input type ="submit"  value="go"> <br>   </form>   </body>   </html>   welcome.jsp <html>   <body>   <%   response.sendRedirect("    %>   </form>   </body>   </html> 

31 4-JSP implicit object: config
config object -Stores the Servlet configuration data. It can be used to get initialization parameter for a particular JSP page. Generally, it is used to get initialization parameter from the web.xml file. It is created by the web container for each jsp page. index.html web.xml <html>  <body>  <form  action="welcome.jsp“ >   <input  type ="text" name="uname“ >   <input  type ="submit"  value="go"> <br>   </form>   </body>  </html>   <web-app>      <servlet>   <servlet-name>sonoojaiswal</servlet-name>   <jsp-file>/welcome.jsp</jsp-file>   <init-param>   <param-name>dname</param-name>   <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>   </init-param>   </servlet>   <servlet-mapping>   <url-pattern>/welcome</url-pattern>   </servlet-mapping>   </web-app>   welcome.jsp <html>  <body>   <% out.print("Welcome "+request.getParameter("uname")); String driver = config.getInitParameter("dname"); out.print("driver name is="+driver); %> </form>  </body>  </html> 

32 5-JSP implicit object: application
In JSP, application is an implicit object of type ServletContext. It is created only once by the web container when application or project is deployed on the server. It can be used to get initialization parameter from the configuration file (web.xml). It can also be used to get, set or remove attribute from the application scope. This initialization parameter can be used by all jsp pages. index.html web.xml <html>  <body>  <form  action="welcome.jsp“ >   <input  type ="text" name="uname“ >   <input  type ="submit"  value="go"> <br>   </form>   </body>  </html>   <web-app> <servlet> <servlet-name>sonoojaiswal</servlet-name> <jsp-file>/welcome.jsp</jsp-file> </servlet> <servlet-mapping> <url-pattern>/welcome</url-pattern> </servlet-mapping> <context-param> <param-name>dname</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </context-param> </web-app> welcome.jsp <html>  <body>   <% out.print("Welcome "+request.getParameter("uname")); String driver=application.getInitParameter("dname"); out.print("driver name is="+driver); %> </form>  </body>  </html> 

33 6-JSP implicit object: session object
The Java developer can use this object to set, get or remove attribute or to get session information and Session Tracking in JSP. Cookies – a small text file stored on the clients machine. Cookie can be disables in the browser settings so are not always available. URL rewriting – store session information in the URL. Works when cookies are not supported but can make bookmarking of web pages a problem because they have session specific information at the end of a URL. index.html welcome.jsp <html>  <body>  <form  action="welcome.jsp“ >   <input  type ="text" name="uname“ >   <input  type ="submit"  value="go"> <br>   </form>   </body>  </html>   <html>  <body>   <%       String name = request.getParameter("uname");   out.print("Welcome "+name);      session.setAttribute("user", name);      <a href="second.jsp"> second jsp page </a>   %>  </form>  </body>  </html>  second.jsp <html> <body> <% String name = (String)session.getAttribute("user"); out.print("Hello "+name); %> </body> </html>  

34 6-JSP implicit object: session object
A session object uses a key / value combination to store information. To retrieve information from a session: session.getValue(“msg”) The return type of the method getValue is Object , so you will need to typecast to get the required value. If there is not a session key with that name , null is returned. To set a session key with a value: session.putValue (“msg” , val)

35 7-JSP implicit object: pageContext
In JSP, pageContext is an implicit object of type PageContext class. It can be used to set, get or remove attribute from one of the following scopes: page, request, session, application In JSP, page scope is the default scope index.html welcome.jsp <html>   <body>  <form  action="welcome.jsp“ >   <input  type ="text" name="uname“ >   <input  type ="submit"  value="go"> <br>   </form>   </body>  </html>   <html>  <body>   <%    String name=request.getParameter("uname"); out.print("Welcome "+name); pageContext.setAttribute( "user",name,PageContext.SESSION_SCOPE); <a href="second.jsp">second jsp page</a>   %>  </form>  </body>  </html>  second.jsp <html> <body> <% String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE); out.print("Hello "+name); %> </body> </html>  

36 8-JSP implicit object: page
In JSP, page is an implicit object of type Object class. page object -Represents the JSP page and is used to call any methods defined by the servlet class. This object is assigned to the reference of auto generated servlet class. It is written as: Object page=this; For using this object, it must be cast to Servlet type. For example: <% (HttpServlet) page.log("message"); %> Since, it is of type Object it is less used because you can use this object directly in jsp. <% this.log("message"); %>

37 9-JSP implicit object: exception
In JSP, exception is an implicit object of type java.lang.Throwable. It can be used to print the exception. But it can only be used in error pages. It is better to learn it after page directive. error.jsp page isErrorPage="true" %> <html> <body> Sorry following exception occurred: <%= exception %> </body> </html>

38 Exception Handling in JSP
The exception is normally an object that is thrown at runtime. Exception Handling is the process to handle the runtime errors. There may occur exception any time in your web application. So handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform exception handling: By errorPage and isErrorPage attributes of page directive By <error-page> element in web.xml file

39 JSP Error Example: using page directive
In this case, you must define and create a page to handle the exceptions In pages where the exception may occur, define the errorPage attribute of page directive, as in the process.jsp page. There are 3 files: index.jsp for input values process.jsp for dividing the two numbers and displaying the result error.jsp for handling the exception index.jsp <html>  <body>  <form action="process.jsp"> No1:<input type="text" name="n1" /><br/><br/> No1:<input type="text“ name="n2" /><br/><br/> <input type="submit" value="divide"/> </form> </body>  </html>   process.jsp <html>  <body>   <%    String num1=request.getParameter("n1"); String num2=request.getParameter("n2"); int a=Integer.parseInt(num1); int b=Integer.parseInt(num2); int c=a/b; out.print("division of numbers is: "+c); %>  </body>  </html>  error.jsp page isErrorPage="true" %> <html> <body> Sorry following an exception is occurred Exception is: <%= exception %> </body> </html>

40 Examples: Standard Actions
Standard actions are well known tags that affect the run time behavior of the JSP and the response sent back to the client. Some commonly used tag actions types are: <jsp:useBean> <jsp:setProperty> <jsp:getProperty> <jsp:param> <jsp:include> <jsp:forward> <jsp:plugin>


Download ppt "Introduction to JSP Java Server Pages"

Similar presentations


Ads by Google