Your SlideShare is downloading. ×
JEE Course - The Web Tier
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

JEE Course - The Web Tier

2,452
views

Published on

The Web tier section of the JEE course

The Web tier section of the JEE course

Published in: Technology, Education

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,452
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
118
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. The Web Tier Copyright © Oded Nissan 2009
  • 2.
    • Overview
    • Web Applications
    • Servlets
    • Java Server Pages (JSP)
    • The Standard Tag Library (JSTL)
    • Overview of Java Server Faces (JSF)
    • Summary
    The Web Tier Copyright © Oded Nissan 2009
  • 3. Overview Copyright © Oded Nissan 2009
  • 4.
    • The presentation tier in the JEE architecture.
    • Contains technologies that support creating web applications and serving web content.
    • Implemented by the web container part of the JEE application server.
    What is the Web Tier in JEE ? Copyright © Oded Nissan 2009
  • 5. What is the Web Tier in JEE ? Copyright © Oded Nissan 2009
  • 6.
    • There are two types of Web Applications:
    • Presentation Oriented - A presentation-oriented web application generates interactive web pages and dynamic content in response to requests. The JSP and Servlet technologies are used in this type of an application.
    • Service Oriented -A service-oriented web application implements the endpoint of a web service. Presentation-oriented applications are often clients of service-oriented web applications. Web services and Servlets are used in a Services Oriented web application.
    Types of Web Applications Copyright © Oded Nissan 2009
  • 7.
    • What is the difference ?
    • A web server serves static content and serves dynamic content by running special plugins.
    • A web container runs the JEE web tier technologies, it serves both dynamic and static content, in fact it contains a web server.
    Web Container and Web Server Copyright © Oded Nissan 2009
  • 8. Web Applications Copyright © Oded Nissan 2009
  • 9.
    • Web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, JSP pages, or web service endpoints.
    • The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component.
    Web Applications Copyright © Oded Nissan 2009
  • 10. Web Applications Copyright © Oded Nissan 2009
  • 11.
    • Servlets are Java programming language classes that dynamically process requests and construct responses.
    • JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
    • Although servlets and JSP pages can be used interchangeably, each has its own strengths. Servlets are best suited for service-oriented applications application, JSP pages are more appropriate for generating a web based UI.
    Web Application Technologies Copyright © Oded Nissan 2009
  • 12.
    • The relation between web tier technologies:
    Web Application Technologies Copyright © Oded Nissan 2009
  • 13.
    • Develop the web component code.
    • Develop the web application deployment descriptor.
    • Compile the web application components and helper classes referenced by the components.
    • Optionally package the application into a deployable unit.
    • Deploy the application into a web container.
    • Access a URL that references the web application.
    The Development Life Cycle Copyright © Oded Nissan 2009
  • 14.
    • A web module is the smallest deployable and usable unit of web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification.
    • A web module can be deployed on the application server, or packaged in an EAR file. Several web modules can be packaged into the same EAR file. Each web module represents a web application.
    Web Modules Copyright © Oded Nissan 2009
  • 15.
    • A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources, such as images, are stored.
    • The document root contains a subdirectory named WEB-INF, which contains the following files and directories:
    • web.xml: The web application deployment descriptor
    • Tag library descriptor files classes: A directory that contains server-side classes : servlets, utility classes, and JavaBeans components
    • tags: A directory that contains tag files, which are implementations of tag libraries
    • lib: A directory that contains JAR archives of libraries called by server-side classes
    The Web Module Structure Copyright © Oded Nissan 2009
  • 16. The Web Module Structure Copyright © Oded Nissan 2009
  • 17.
    • A web module must be packaged into a WAR whenever you want to distribute the web module. You package a web module into a WAR by executing the jar command in a directory laid out in the format of a web module, by using the Ant utility, or by using the IDE tool of your choice.
    • A context root identifies a web application in a Java EE server. You specify the context root when you deploy a web module. A context root must start with a forward slash (/) and end with a string.
    Packaging Web Modules Copyright © Oded Nissan 2009
  • 18. Servlets Copyright © Oded Nissan 2009
  • 19.
    • Servlets are server side Java classes that handle client requests and can generate dynamic content.
    • Servlets can handle all types of requests but are specifically used to handle HTTP requests.
    • Servlets implement a specific API. Currently defined by the Servlet 2.5 spec in JEE 5.
    What are Servlets ? Copyright © Oded Nissan 2009
  • 20.
    • The javax.Servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.
    • All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the Generic Servlet class provided with the Java Servlet API.
    • TheHttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
    Servlets Copyright © Oded Nissan 2009
  • 21. The Servlet LifeCycle Copyright © Oded Nissan 2009
  • 22.
    • Initialization is the first phase of the Servlet life cycle and represents the creation and initialization of resources the Servlet may need to service requests. Initialization is performed by the Servlet API’s init() method.
    • The service phase of the Servlet life cycle represents all interactions with requests until the Servlet is destroyed. This phase is performed by the service() method in the Servlet API.
    • The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a container. This is implemented by the destroy() method of the Servlet API.
    The Servlet LifeCycle Copyright © Oded Nissan 2009
  • 23.
    • An HttpServlet handles HTTP requests and adds helper methods to deal with different HTTP request types.
    • An HttpServlet contains methods to read HTTP headers, cookies and request parameters.
    The Servlet LifeCycle Copyright © Oded Nissan 2009
  • 24. The HttpServlet Life Cycle Copyright © Oded Nissan 2009
  • 25.
    • import javax.servlet.*;
    • import javax.servlet.http.*;
    • public class HelloWorld extends HttpServlet {
    • public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    • {
    • response.setContentType("text/html");
    • PrintWriter out = response.getWriter();
    • out.println(&quot;<html>&quot;);
    • out.println(&quot;<head>&quot;);
    • out.println(&quot;<title>Hello World!</title>&quot;);
    • out.println(&quot;</head>&quot;);
    • out.println(&quot;<body>&quot;);
    • out.println(&quot;<h1>Hello World!</h1>&quot;);
    • out.println(&quot;</body>&quot;);
    • out.println(&quot;</html>&quot;);
    • }
    • }
    Servlet Example Copyright © Oded Nissan 2009
  • 26.
    • A servlet class is compiled into the WEB-INF/classes directory of the web application.
    • The servlet should also be defined in the web.xml deployment descriptor of the web application.
    • The deployment descriptor maps the servlet to a URL and specifies initialization parameters for the servlet.
    Servlet Deployment Copyright © Oded Nissan 2009
  • 27.
    • A deployment descriptor example:
    • < servlet >
    • < servlet-name > SnoopServlet </ servlet-name >
    • < servlet-class >
    • test.SnoopServlet
    • </ servlet-class >
    • </ servlet >
    • < servlet-mapping >
    • < servlet-name > SnoopServlet </ servlet-name >
    • < url-pattern > /snoop </ url-pattern >
    • </ servlet-mapping >
    Servlet Deployment Copyright © Oded Nissan 2009
  • 28.
    • After the web container loads and instantiates the servlet class and before it delivers requests from clients, the web container initializes the servlet. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities, you override the init method of the Servlet interface.
    • A servlet that cannot complete its initialization process should throw UnavailableException.
    Initializing a Servlet Copyright © Oded Nissan 2009
  • 29.
    • Setting an initialization value in the web.xml:
    • < servlet >
    • < description ></ description >
    • < display-name > ExampleServlet1 </ display-name >
    • < servlet-name > ExampleServlet1 </ servlet-name >
    • < servlet-class > test.servlets.ExampleServlet1 </ servlet-class >
    • < init-param >
    • < description ></ description >
    • < param-name > myparam </ param-name >
    • < param-value > Some Value </ param-value >
    • </ init-param >
    • </ servlet >
    Initializing a Servlet Copyright © Oded Nissan 2009
  • 30.
    • Reading an initialization value:
    • /**
    • * @see Servlet#init(ServletConfig)
    • */
    • public void init(ServletConfig config) throws ServletException {
    • this . value = config.getInitParameter( &quot;myparam&quot; );
    • }
    Initializing a Servlet Copyright © Oded Nissan 2009
  • 31.
    • The service provided by a servlet is implemented in the service method of a GenericServlet, in the do Method methods (where Method can take the value Get, Delete, Options, Post, Put, or Trace) of an HttpServlet object, or in any other protocol-specific methods defined by a class that implements the Servlet interface.
    • The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information.
    The Service Method Copyright © Oded Nissan 2009
  • 32.
    • A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing request data:
    • String bookId = request.getParameter(&quot;Add&quot;);
      • if (bookId != null) {
      • Book book = bookDB.getBook(bookId);
      • }
    Reading Request Information Copyright © Oded Nissan 2009
  • 33.
    • Query strings are composed of a set of parameters and values. Individual parameters are retrieved from a request by using the getParameter method. There are two ways to generate query strings:
    • A query string can explicitly appear in a web page. For example, an HTML page generated by CatalogServlet could contain the link
    • <a href=&quot;/bookstore1/catalog?Add=101&quot;>Add To Cart</a>. CatalogServlet extracts the parameter named Add as follows:
    • String bookId = request.getParameter(&quot;Add&quot;);
    • A query string is appended to a URL when a form with a GET HTTP method is submitted.
    HTTP Query Strings Copyright © Oded Nissan 2009
  • 34.
    • A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow you to:
      • Retrieve an output stream to use to send data to the client. To send character data, use the PrintWriter returned by the response’s getWriter method. To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream.
      • Indicate the content type (for example, text/html) being returned by the response with the setContentType(String) method. This method must be called before the response is committed.
      • Indicate whether to buffer output with the setBufferSize(int) method. By default, any content written to the output stream is immediately sent to the client. Buffering allows content to be written before anything is actually sent back to the client, thus providing the servlet with more time to set appropriate status codes and headers or forward to another web resource.
    Constructing Responses Copyright © Oded Nissan 2009
  • 35.
    • It is often useful to include another web resource (for example, banner content or copyright information) in the response returned from a web component. To include another resource, invoke the include method of a RequestDispatcher object:
    • include(request, response);If the resource is static, the include method enables programmatic server-side includes. If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then include the result of the execution in the response from the containing servlet. An included web component has access to the request object, but it is limited in what it can do with the response object:
      • It can write to the body of the response and commit a response.
      • It cannot set headers or call any method (for example, setCookie) that affects the headers of the response.
    Including Other Resources Copyright © Oded Nissan 2009
  • 36.
    • Example code:
    • RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(&quot;/banner&quot;);
    • if (dispatcher != null)
    • dispatcher.include(request, response); }
    Including Other Resources Copyright © Oded Nissan 2009
  • 37.
    • To transfer control to another web component, you invoke the forward method of a RequestDispatcher. When a request is forwarded, the request URL is set to the path of the forwarded page.
    • Example:
    • public void doGet(HttpServletRequest request, HttpServletResponse response)
    • {
      • RequestDispatcher dispatcher = request. getRequestDispatcher(&quot;/template.jsp&quot;);
      • if (dispatcher != null)
        • dispatcher.forward(request, response);
        • }
        • }
    Forwarding to Another Resource Copyright © Oded Nissan 2009
  • 38.
    • A redirect instructs the browser to fetch another resource in order to complete the request.
    • The redirect is a two step process that includes two roundtrip to the server.
    • Example:
    • protected void  doPost(HttpServletRequest request, 
    • HttpServletResponse response)                        throws  ServletException, IOException {       String name = request.getParameter(&quot;username&quot;);      String password = request.getParameter(&quot;password&quot;);      if (name.equals(&quot;James&quot;)&& password.equals(&quot;abc&quot;))
    • {        response.sendRedirect(&quot;/SendRedirect/ValidUserServlet&quot;);      }
    Redirecting to Another Resource Copyright © Oded Nissan 2009
  • 39.
    • In general, a forward should be used if the operation can be safely repeated upon a browser reload of the resulting web page; otherwise, redirect must be used.
    • Typically, if the operation performs an edit on the datastore, then a redirect, not a forward, is required. This is simply to avoid the possibility of inadvertently duplicating an edit to the database.
    Forward vs. Redirect Copyright © Oded Nissan 2009
  • 40.
    • Sessions are represented by an HttpSession object. You access a session by calling the getSession method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one.
    • You can associate object-valued attributes with a session by name. Such attributes are accessible by any web component that belongs to the same web context and is handling a request that is part of the same session.
    Managing Sessions Copyright © Oded Nissan 2009
  • 41.
    • public class CashierServlet extends HttpServlet
    • {
    • public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    • {
    • // Get the user’s session and shopping cart
    • HttpSession session = request.getSession();
    • ShoppingCart cart = (ShoppingCart)session. getAttribute(&quot;cart&quot;);
    • ...
    • // Determine the total price of the user’s books
    • double total = cart.getTotal();
    • … ..
    • }
    Managing Sessions Example Copyright © Oded Nissan 2009
  • 42.
    • Sessions are maintained internally by the web container using either of two mechanisms:
      • Cookies - a session cookie is passed between the client and the server.
      • URL rewriting – a special client id is encoded is all requests sent to the server. This requires that we encode this client id in all links using the encodeURL() method of HttpServletResponse.
    Managing Sessions Copyright © Oded Nissan 2009
  • 43.
    • A Filter is a component that intercepts a request sent to a resource in a Web Application. Filters exist as part of a chain, with the last link in the chain being the requested resource. A Filter can choose to pass the request on, in which case the request will be forwarded to either the next Filter in the Filter chain or, if this is the last Filter in the chain, to the requested resource.
    • The Filter also sees the response before it is returned to the client.
    • Makes use of the GOF Chain of Responsibility pattern.
    Filters Copyright © Oded Nissan 2009
  • 44. Filters Copyright © Oded Nissan 2009
  • 45.
    • The Filter life cycle is similar to the Servlet life cycle.
    The Filter Life Cycle Copyright © Oded Nissan 2009
  • 46.
    • A Filter must implement the javax.servlet.Filter interface.
      • The init() method is invoked when the container first loads the Filter.
      • The doFilter() method is where all the work is done by a Filter. Three parameters are passed into the method: an instance of a ServletRequest, ServletResponse, and FilterChain object.
      • The destroy() method is called when the Filter is unloaded from memory. Typically
    Writing a Filter Copyright © Oded Nissan 2009
  • 47.
    • public class HelloWorldFilter implements Filter {
    • public void init(FilterConfig config)
    • { }
    • public void doFilter(ServletRequest req, ServletResponse res, FilterChain filter) throws IOException, ServletException {
    • HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; response.setContentType(&quot;text/html&quot;);
    • PrintWriter out = response.getWriter();
    • out.println(&quot;<html>&quot;);
    • out.println(&quot;<body>&quot;);
    • out.println(&quot;<h1>Hello World!</h1>&quot;);
    • out.println(&quot;</body>&quot;);
    • out.println(&quot;</html>&quot;);
    • return;
    • }
    Writing a Filter Copyright © Oded Nissan 2009
  • 48.
    • A Filter is mapped to a URL is the web.xml file.
    • We can also use wildcards to make a Filter run for a group of URLs.
    • <filter>
    • <filter-name>HelloWorldFilter</filter-name>
    • <filter-class>com.jspbook.HelloWorldFilter</filter-class>
    • </filter>
    • <filter-mapping>
    • <filter-name>HelloWorldFilter</filter-name>
    • <url-pattern>/HelloWorldFilter</url-pattern>
    • </filter-mapping>
    Filter Configuration in web.xml Copyright © Oded Nissan 2009
  • 49.
    • A Filter can invoke other filters in the chain by calling the doFilter() method of the FilterChain object.
    • If a Filter returns from its doFilter() method without calling the chain, the chain is broken.
    Filter Chains Copyright © Oded Nissan 2009
  • 50.
    • A Servlet instance is shared by multiple clients. The same instance is initialized once and then used by different clients.
    • Concurrent client requests are run by the web container in different threads but use the same Servlet instance.
    • Therefore, Servlets must be written to be thread safe.
    Servlets and Concurrency Copyright © Oded Nissan 2009
  • 51.
    • If our Servlet cannot be thread safe then we need to implement the SingleThreadedModel interface.
    • The SingleThreadedModel interface is a marker interface that signals to the web container to prevent concurrent access to the same Servlet instance.
    • The container can implement this by serializing client requests, creating a new instance for each client request or using a Servlet instance pool.
    Servlets and Concurrency Copyright © Oded Nissan 2009
  • 52. Exercise Copyright © Oded Nissan 2009
  • 53. Java Server Pages Copyright © Oded Nissan 2009
  • 54.
    • A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML , SVG , WML , and XML ), and JSP elements, which construct dynamic content.
    • The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page.
    What is a JSP Page ? Copyright © Oded Nissan 2009
  • 55.
    • JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content.
    • Main JSP features:
      • A language for developing JSP pages, which are text-based documents that describe how to process a request and construct a response
      • An expression language for accessing server-side objects
      • Mechanisms for defining extensions to the JSP language
    Java Server Pages Copyright © Oded Nissan 2009
  • 56.
    • JSP pages are compiled by an internal web container compiler to Servlets.
    • A JSP is a simple method of creating a text-producing Servlet.
    • JSP pages help mix dynamic and static content for creating a web application UI.
    • Can be accessed just like static HTML pages.
    Java Server Pages Copyright © Oded Nissan 2009
  • 57. The JSP Life Cycle Copyright © Oded Nissan 2009
  • 58.
    • Scriptlets
    • Expressions
    • Declarations
    • Directives
    • Tags
    JSP Page Elements Copyright © Oded Nissan 2009
  • 59.
    • Scriptlets provide a method for directly inserting bits of Java code between chunks of template text. A scriptlet is defined with a start ,<%, an end, %>, with code between. Using Java, the script is identical to normal Java code but without needing a class declaration or any methods. Scriptlets are great for providing low-level functionality such as iteration, loops, and conditional statements, but they also provide a method for embedding complex chunks of code within a JSP.
    Scriptlets Copyright © Oded Nissan 2009
  • 60.
    • <html>
    • <head>
    • <title>Loop Example</title>
    • </head>
    • <body>
    • <%
    • for (int i=0; i<5;i++) {
    • %>
    • Repeated 5 Times.<br>
    • <%
    • } %>
    • </body>
    • </html>
    Scriptlet Example Copyright © Oded Nissan 2009
  • 61. Scriptlet Example Copyright © Oded Nissan 2009
  • 62.
    • Expressions provide an easy method of sending out dynamic strings to a client. An expression must have a start, <%=, end, %>, and an expression between.
    • Expressions always send a string of text to a client, but the object produced as a result of an expression does not have to always end up as an instance of a String object.
    • Any object left as the result of an expression automatically has its toString() method called to determine the value of the expression. If the result of the expression is a primitive, the primitive's value represented as a string is used.
    Expressions Copyright © Oded Nissan 2009
  • 63.
    • <html>
    • <head>
    • <title>Iteration Example</title>
    • </head>
    • <body>
    • <%
    • String[] strings = new String[4];
    • strings[0] = &quot;Alpha&quot;;
    • strings[1] = &quot;in&quot;;
    • strings[2] = &quot;between&quot;;
    • strings[3] = &quot;Omega&quot;;
    • for (int i=0; i<strings.length;i++) {
    • %>
    • String[<%= i %>] = <%= strings[i] %>
    • <br>
    • <% } %>
    • </body>
    • </html>
    Expression Example Copyright © Oded Nissan 2009
  • 64. Expression Example Copyright © Oded Nissan 2009
  • 65.
    • A declaration is used like a scriptlet to embed code in a JSP, but code embedded by a declaration appears outside of the _jspService() method. For this reason code embedded in a declaration can be used to declare new methods and global class variables, but caution should be taken because code in a declaration is not thread-safe, unless made so by the writer of that code.
    Declarations Copyright © Oded Nissan 2009
  • 66.
    • <%!
    • int pageCount = 0;
    • void addCount()
    • {
    • pageCount++;
    • } %>
    • <html>
    • <head>
    • <title>PageCounter.jsp</title>
    • </head>
    • <body>
    • <% addCount(); %>
    • This page has been visited <%= pageCount %> times.
    • </body>
    • </html>
    Declarations Example Copyright © Oded Nissan 2009
  • 67.
    • Directives are messages to a JSP container.
    • They do not send output to a client, but are used to define page attributes, which custom tag libraries use and which other pages include.
    • All directives use the following syntax:
      • %@ directive {attribute=&quot;value&quot;}* %>
    Directives Copyright © Oded Nissan 2009
  • 68.
    • The page directive provides page-specific information to a JSP container. This information includes settings such as the type of content the JSP is to produce, the default scripting language of the page, and code libraries to import for use
    • The main attributes of the page directive:
      • Import – followed by classes to be imported.
      • Session - attribute indicates that the page requires participation in an HTTP session. Possible values are true/false.
      • errorPage - The errorPage attribute defines a relative URL to a resource in the Web Application to which any Java programming language Throwable object thrown but not caught by the page implementation is forwarded for error processing.
      • isErrorPage -The isErrorPage attribute indicates if the current JSP page is intended to be an error page for other JSP. If true, then the implicit scripting variable exception is defined, and its value is a reference to the offending Throwable object.
    The <%@page%> Directive Copyright © Oded Nissan 2009
  • 69.
      • Import – followed by classes to be imported.
      • Session - attribute indicates that the page requires participation in an HTTP session. Possible values are true/false.
      • errorPage - The errorPage attribute defines a relative URL to a resource in the Web Application to which any Java programming language Throwable object thrown but not caught by the page implementation is forwarded for error processing.
      • isErrorPage -The isErrorPage attribute indicates if the current JSP page is intended to be an error page for other JSP. If true, then the implicit scripting variable exception is defined, and its value is a reference to the offending Throwable object.
      • contentType – specifies the character encoding for the JSP page, and for the response of the JSP page and the MIME type for the response of the JSP page
      • pageEncoding - defines the character encoding for the JSP.
    The Page Directive’s main attributes Copyright © Oded Nissan 2009
  • 70.
    • The include directive is used to include text and/or code at translation time of a JSP.
    • The include directive always follows the same syntax, <%@ include file=&quot;relativeURL&quot; %>, where the value of relativeURL is replaced with the file to be inserted.
    • Files included must be part of a Web Application.
    The <%@ include %> Directive Copyright © Oded Nissan 2009
  • 71.
    • The taglib directive informs a container what bits of markup on the page should be considered custom code and what code the markup links to.
    • The taglib directive always follows the same syntax,<%@taglib uri=&quot;uri&quot; prefix=&quot;prefixOfTag&quot; %>, where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.
    The <%@ taglib %> Directive Copyright © Oded Nissan 2009
  • 72.
    • JSP implicit objects are automatically declared by a JSP container and are always available for use by scripting elements.
    • The following implicit objects are available:
    • config - The config implicit object is an instance of a javax.servlet.ServletConfig object. response
    • request - an instance of a javax.servlet.http.HttpServletRequest object.
    • response - an instance of a javax.servlet.http.HttpServletRequest object.
    • session - an instance of a javax.servlet.http.HttpSession object.
    • application - an instance of a javax.servlet.ServletContext object. The application implicit object represents a Servlet's view of a Web Application and is equivalent to calling the ServletConfig getServletContext() method.
    • out - an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
    Implicit Objects Copyright © Oded Nissan 2009
  • 73.
    • Exceptions thrown from a Servlet or JSP can be handled on an individual basis or on an application-wide basis.
    • There are advantages to each of these approaches, and both deserve a full explanation. Handling exceptions on an individual basis slightly differs between Servlets and JSP, but primarily involves directly using try-catch-finally statements.
    • The general approach to Web Application error handling is through using web.xml to direct exceptions to custom-defined error pages.
    Error Handling Copyright © Oded Nissan 2009
  • 74.
    • In addition to the try-catch-finally statement, JavaServer Pages can use the page directive to specify a page that uncaught exceptions are passed to.
    • The page directive's errorPage attribute can be assigned a relative URL value representing a JSP or Servlet especially designed to be an error page.
    • A JSP designed to be an error page can set the page directive isErrorPage attribute to true; this makes the exception implicit scripting variable automatically available.
    Error Handling Copyright © Oded Nissan 2009
  • 75.
    • Throwing an Exception
    • <%@ page errorPage=&quot;ErrorPage.jsp&quot; %>
    • <%
    • if (true) throw new Exception(&quot;An Exception!&quot;);
    • %>
    • A sample Error page:
    • <%@ page isErrorPage=&quot;true&quot; %>
    • <html>
    • <head> <title>An Error Has Occurred!</title> </head>
    • <body>
    • <h3>An Error Has Occurred</h3>
    • Sorry, but this site is unavailable to render the service you requested. A bug in the system has caused an error to occur.
    • Please send a description of the problem to
    • <%= application.getInitParameter(&quot;admin email&quot;) %>.
    • </body> </html>
    Error Handling Copyright © Oded Nissan 2009
  • 76.
    • There are three generic types of Throwable objects thrown by Servlets and JSP: IOException, ServletException, and JspException.
    • When a Servlet is processing a call to the service() method, it has the option of throwing either an instance of an IOException or ServletException. Any JSP processing a request has the option of throwing an instance of a JspException object.
    • Catching all three of these exceptions ensures that all checked exceptions thrown by a Servlet or JSP result in a custom error page
    Error Handling Copyright © Oded Nissan 2009
  • 77.
    • We can configure an error page for all exception types that subclass Exception:
    • <error-page>
    • <exception-type>java.lang.Exception</exception-type> <location>/ErrorPage.jsp</location>
    • </error-page>
    • The same error page mechanism available for catching thrown exceptions can be applied to responses with undesired HTTP headers:
    • <error-page>
    • <error-code>HTTP Code</error-code>
    • <location>Relative URL</location>
    • </error-page>
    Error Handling Copyright © Oded Nissan 2009
  • 78.
    • A Java Bean is a class that implements the java.io.Serializable interface, provides a no argument constructor and getter and setter methods for it member variables.
    • JavaBeans are never required for use with JSP and Servlets, but they commonly appear because they are helpful for passing scoped information.
    Java Beans Copyright © Oded Nissan 2009
  • 79.
    • public class ExampleBean implements java.io.Serializable
    • {
    • String value;
    • public ExampleBean()
    • { }
    • public String getValue()
    • {
    • return value;
    • }
    • public void setValue(String value)
    • {
    • this.value = value;
    • }
    • }
    Java Bean Example Copyright © Oded Nissan 2009
  • 80.
    • The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the useBean tag is as follows:
    • <jsp:useBean id=&quot;bean's name&quot; scope=&quot;bean's scope&quot; typeSpec/>
    Java Beans Copyright © Oded Nissan 2009
  • 81.
    • page- The page value places the JavaBean as an attribute to the javax.servlet.jsp.PageContext for the current page. The bean is discarded upon completion of the current request.
    • request - The request value places the JavaBean in request scope. The JavaBean is available from the current page's ServletRequest object via the getAttribute() method. The JavaBean is discarded upon completion of the current request.
    • session - The session value places the JavaBean in session scope. The JavaBean can be accessed via the getAttribute() method of the HttpSession object associated with a client. The JavaBean automatically persists until the session is invalidated. A translation time error is raised if the session value is used on a JSP that has declared it is not participating in a session.
    • application - The application value places the JavaBean in application scope. The JavaBean persists as long as the application does and can be accessed via the getAttribute() method of the Web Application's ServletContext object.
    Java Beans Scopes Copyright © Oded Nissan 2009
  • 82.
    • Along with the id attribute and scope attribute, the useBean action needs to know what Java class should be initialized as the JavaBean. In most cases this is done by simply using the class or type attribute and specifying as a value the fully qualified Java class name.
    • Example:
      • <html>
      • <head> <title>useBean Example</title> </head>
      • <body>
      • <jsp:useBean id=&quot;date&quot; class=&quot;java.util.Date&quot; />
      • The date/time is <%= date %>
      • </body>
      • </html>
    Java Beans Copyright © Oded Nissan 2009
  • 83.
    • Complementing the useBean action are the getProperty and setProperty actions.
    • The getProperty action provides a convenient way of invoking a get method, and the setProperty action provides a convenient way of invoking a set method.
    • With all three of the bean-manipulating actions, it is now possible to remove the majority of scripting elements.
    Java Beans Copyright © Oded Nissan 2009
  • 84.
    • The geProperty action is used to get bean values:
      • <jsp:getProperty name=&quot;name&quot; property=&quot;method&quot; />
    • The name attribute references the name of a JavaBean previously introduced to the JSP by the useBean action. The property attribute is the name of the get method that should be invoked. The results of the get method are placed in the implicit out object after being converted to a string either by calling the toString() method or straight conversion in the case of primitives.
    <jsp:getProperty/> Copyright © Oded Nissan 2009
  • 85.
    • The setProperty action is used to set values of a bean:
      • <jsp:setProperty name=&quot;name&quot; property=&quot;method&quot; valueAttribute />
    • The name and property attributes are required and provide the name of the JavaBean and set method to be invoked on the bean. In addition to the name and property attributes, a value needs to be provided for a set method of the property's value. The value can be specified in one of two ways:
    <jsp:setProperty/> Copyright © Oded Nissan 2009
  • 86.
    • <html>
    • <head> <title>useBean Example</title> </head>
    • <body>
    • <jsp:useBean id=&quot;user&quot; class=&quot;com.jspbook.User&quot; /> <jsp:setProperty name=&quot;user&quot; property=&quot;name&quot; value=&quot;Bob&quot;/>
    • <jsp:setProperty name=&quot;user&quot; property=&quot;password&quot; value=&quot;password&quot;/>
    • Hello <jsp:getProperty name=&quot;user&quot; property=&quot;name&quot;/>,
    • welcome to this web page!
    • </body>
    • </html>
    Example Copyright © Oded Nissan 2009
  • 87.
    • In most cases Java Beans will be initialized by a Servlet and then passed to a JSP page.
    • This mechanism is commonly used in many MVC pattern implementations.
    • The initializing Servlet creates and populates the bean and puts it in the request using the setAttribute method before forwarding the request to the JSP page.
    Initializing Beans Copyright © Oded Nissan 2009
  • 88.
    • JSP pages are deployed like static web resources (HTML files, images etc.) into the web application’s web resource directory.
    • JSP pages are compile by the container the first time they are accessed. They are recompiled if changed.
    • JSP pages can also be precompiled, this is usually implemented by a special ant task or as part of the application deployment process.
    JSP Deployment Copyright © Oded Nissan 2009
  • 89.
    • JSP can be extended to include custom tags that encapsulate business or presentation logic.
    • These tags are called custom tags and can be integrated into an existing application by including a jar file and the proper <%@ taglib %> directive.
    • Custom tags provide a clean alternative to “heavy” and reusable scriptlet code.
    Custom Tags Copyright © Oded Nissan 2009
  • 90.
    • A Tag Library is a collection of custom tags typically designed to complement each other and accomplish a common goal. The Tags within the library are written either in Java or as JSP fragments and can be used by a JSP as described by a TLD (Tag Library Descriptor).
    Custom Tags Copyright © Oded Nissan 2009
  • 91. Custom Tags Copyright © Oded Nissan 2009
  • 92.
    • <%@taglib prefix=&quot;in&quot; uri=&quot;/WEB-INF/i18n.tld&quot; %>
      • <html>
        • <head>
        • <in:title id=&quot;groups&quot;/>
        • </head> ...
        • This is an example of a custom tag named title in an i18n tag library. The tag is passed an ID attribute that it will typically use as an index into a resource bundle, extracting the correct text based on the locale of the client. It is this extracted text that is displayed as the result of the tag and that appears as the page title.
    Using a Custom Tag Copyright © Oded Nissan 2009
  • 93. Exercise Copyright © Oded Nissan 2009
  • 94. The Java Standard Tag Library (JSTL) Copyright © Oded Nissan 2009
  • 95.
    • The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP applications. Instead of mixing tags from numerous vendors in your JSP applications, JSTL allows you to employ a single, standard set of tags. This standardization allows you to deploy your applications on any JSP container supporting JSTL and makes it more likely that the implementation of the tags is optimized.
    • JSTL has tags such as iterators and conditionals for handling flow control, tags for manipulating XML documents, internationalization tags, tags for accessing databases using SQL, and commonly used functions.
    The Java Standard Tag Library (JSTL) Copyright © Oded Nissan 2009
  • 96.
    • <c:set var=&quot;bookId&quot; value=&quot;${param.Remove}&quot;/>
    • <jsp:useBean id=&quot;bookId&quot; type=&quot;java.lang.String&quot; />
    • <% cart.remove(bookId); %>
    • <sql:query var=&quot;books&quot; dataSource=&quot;${applicationScope.bookDS}&quot;>
    • select * from PUBLIC.books where id = ? <sql:param value=&quot;${bookId}&quot; />
    • </sql:query>
    JSTL Example Copyright © Oded Nissan 2009
  • 97.
    • http://java.sun.com/products/jsp/jstl/reference/docs/index.html
    • http://onjava.com/pub/a/onjava/2002/03/13/jsp.html
    • http://www.javaworld.com/javaworld/jw-02-2003/jw-0228-jstl.html
    External Resourses Copyright © Oded Nissan 2009
  • 98. Java Server Faces Copyright © Oded Nissan 2009
  • 99.
    • JSF is a web framework developed through the Java Community Process (JCP).
    • Its goal is to ease the development of JEE web applications.
    • JSF is based on Servlet and JSP technologies.
    Java Server Faces Overview Copyright © Oded Nissan 2009
  • 100.
    • JSF makes use of the MVC pattern to separate presentation from behavior.
    • Features a component model to package UI components.
    • Contains a state machine for managing page navigation using XML configuration.
    Java Server Faces (JSF) Copyright © Oded Nissan 2009
  • 101.
    • The Model View Controller pattern provides a clean separation between the presentation logic and business logic.
    • The MVC pattern is the foundation of most web frameworks.
    • Can be implemented by mixing Servlets JSPs and Java Beans.
    The MVC Pattern Copyright © Oded Nissan 2009
  • 102. The MVC Pattern Copyright © Oded Nissan 2009
  • 103.
    • The view part of the MVC pattern is usually implemented using a JSP page.
    • A Java Bean represents the model part.
    • The controller is represented by a Servlet.
    • Business logic is implemented by Java classes or EJBs that are invoked by the controller servlet.
    The MVC Pattern Copyright © Oded Nissan 2009
  • 104.
    • Discussion of the MVC pattern implementation….
    The MVC Pattern Copyright © Oded Nissan 2009
  • 105.
    • What did we discuss ?
      • Overview
      • Web Applications
      • Servlets
      • Java Server Pages
      • Custom Tags
      • JSTL
      • JSF
      • MVC
    Summary Copyright © Oded Nissan 2009