105
The Web Tier Copyright © Oded Nissan 2009

JEE Course - The Web Tier

  • View
    2.650

  • Download
    6

Embed Size (px)

DESCRIPTION

The Web tier section of the JEE course

Citation preview

  • The Web TierCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • OverviewWeb ApplicationsServletsJava Server Pages (JSP)The Standard Tag Library (JSTL)Overview of Java Server Faces (JSF)Summary

    Copyright Oded Nissan 2009The Web Tier

    Copyright Oded Nissan 2009

  • OverviewCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009What is the Web Tier in JEE ?

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009What is the Web Tier in JEE ?

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Types of Web Applications

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Web Container and Web Server

    Copyright Oded Nissan 2009

  • Web ApplicationsCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • 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. Copyright Oded Nissan 2009Web Applications

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009Web Applications

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Web Application Technologies

    Copyright Oded Nissan 2009

  • The relation between web tier technologies:

    Copyright Oded Nissan 2009Web Application Technologies

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009The Development Life Cycle

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Web Modules

    Copyright Oded Nissan 2009

  • 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 descriptorTag library descriptor files classes: A directory that contains server-side classes: servlets, utility classes, and JavaBeans componentstags: 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

    Copyright Oded Nissan 2009The Web Module Structure

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009The Web Module Structure

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Packaging Web Modules

    Copyright Oded Nissan 2009

  • ServletsCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009What are Servlets ?

    Copyright Oded Nissan 2009

  • 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. Copyright Oded Nissan 2009Servlets

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009The Servlet LifeCycle

    Copyright Oded Nissan 2009

  • 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 APIs 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.

    Copyright Oded Nissan 2009The Servlet LifeCycle

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009The Servlet LifeCycle

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009The HttpServlet Life Cycle

    Copyright Oded Nissan 2009

  • 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(""); out.println(""); out.println("Hello World!"); out.println(""); out.println(""); out.println("Hello World!"); out.println(""); out.println(""); } } Copyright Oded Nissan 2009Servlet Example

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Servlet Deployment

    Copyright Oded Nissan 2009

  • A deployment descriptor example: SnoopServlet test.SnoopServlet SnoopServlet /snoop

    Copyright Oded Nissan 2009Servlet Deployment

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Initializing a Servlet

    Copyright Oded Nissan 2009

  • Setting an initialization value in the web.xml: ExampleServlet1 ExampleServlet1 test.servlets.ExampleServlet1 myparam Some Value Copyright Oded Nissan 2009Initializing a Servlet

    Copyright Oded Nissan 2009

  • Reading an initialization value:/** * @see Servlet#init(ServletConfig) */public void init(ServletConfig config) throws ServletException {this.value = config.getInitParameter("myparam");}Copyright Oded Nissan 2009Initializing a Servlet

    Copyright Oded Nissan 2009

  • The service provided by a servlet is implemented in the service method of a GenericServlet, in the doMethod 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. Copyright Oded Nissan 2009The Service Method

    Copyright Oded Nissan 2009

  • 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("Add"); if (bookId != null) { Book book = bookDB.getBook(bookId);}

    Copyright Oded Nissan 2009Reading Request Information

    Copyright Oded Nissan 2009

  • 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 Add To Cart. CatalogServlet extracts the parameter named Add as follows:String bookId = request.getParameter("Add");A query string is appended to a URL when a form with a GET HTTP method is submitted.

    Copyright Oded Nissan 2009HTTP Query Strings

    Copyright Oded Nissan 2009

  • 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 responses 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. Copyright Oded Nissan 2009Constructing Responses

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Including Other Resources

    Copyright Oded Nissan 2009

  • Example code:

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); } Copyright Oded Nissan 2009Including Other Resources

    Copyright Oded Nissan 2009

  • 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("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); }} Copyright Oded Nissan 2009Forwarding to Another Resource

    Copyright Oded Nissan 2009

  • 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:protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ Stringname=request.getParameter("username"); Stringpassword=request.getParameter("password"); if(name.equals("James")&&password.equals("abc")){ response.sendRedirect("/SendRedirect/ValidUserServlet"); } Copyright Oded Nissan 2009Redirecting to Another Resource

    Copyright Oded Nissan 2009

  • 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. Copyright Oded Nissan 2009Forward vs. Redirect

    Copyright Oded Nissan 2009

  • 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. Copyright Oded Nissan 2009Managing Sessions

    Copyright Oded Nissan 2009

  • public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the users session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); ... // Determine the total price of the users books double total = cart.getTotal();..} Copyright Oded Nissan 2009Managing Sessions Example

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Managing Sessions

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Filters

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009Filters

    Copyright Oded Nissan 2009

  • The Filter life cycle is similar to the Servlet life cycle.

    Copyright Oded Nissan 2009The Filter Life Cycle

    Copyright Oded Nissan 2009

  • 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

    Copyright Oded Nissan 2009Writing a Filter

    Copyright Oded Nissan 2009

  • 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("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Hello World!"); out.println(""); out.println(""); return; } Copyright Oded Nissan 2009Writing a Filter

    Copyright Oded Nissan 2009

  • 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. HelloWorldFilter com.jspbook.HelloWorldFilter HelloWorldFilter /HelloWorldFilter

    Copyright Oded Nissan 2009Filter Configuration in web.xml

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Filter Chains

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Servlets and Concurrency

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Servlets and Concurrency

    Copyright Oded Nissan 2009

  • ExerciseCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • Java Server PagesCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009What is a JSP Page ?

    Copyright Oded Nissan 2009

  • 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 responseAn expression language for accessing server-side objectsMechanisms for defining extensions to the JSP language

    Copyright Oded Nissan 2009Java Server Pages

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Java Server Pages

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009The JSP Life Cycle

    Copyright Oded Nissan 2009

  • ScriptletsExpressionsDeclarationsDirectivesTags

    Copyright Oded Nissan 2009JSP Page Elements

    Copyright Oded Nissan 2009

  • Scriptlets provide a method for directly inserting bits of Java code between chunks of template text. A scriptlet is defined with a start ,, 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.

    Copyright Oded Nissan 2009Scriptlets

    Copyright Oded Nissan 2009

  • Loop Example
  • Copyright Oded Nissan 2009Scriptlet Example

    Copyright Oded Nissan 2009

  • Expressions provide an easy method of sending out dynamic strings to a client. An expression must have a start, , 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.

    Copyright Oded Nissan 2009Expressions

    Copyright Oded Nissan 2009

  • Iteration Example
  • Copyright Oded Nissan 2009Expression Example

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Declarations

    Copyright Oded Nissan 2009

  • PageCounter.jsp This page has been visited times. Copyright Oded Nissan 2009Declarations Example

    Copyright Oded Nissan 2009

  • 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="value"}* %> Copyright Oded Nissan 2009Directives

    Copyright Oded Nissan 2009

  • 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 useThe 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.

    Copyright Oded Nissan 2009The Directive

    Copyright Oded Nissan 2009

  • 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 pagepageEncoding - defines the character encoding for the JSP.

    Copyright Oded Nissan 2009The Page Directives main attributes

    Copyright Oded Nissan 2009

  • 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, , where the value of relativeURL is replaced with the file to be inserted. Files included must be part of a Web Application.

    Copyright Oded Nissan 2009The Directive

    Copyright Oded Nissan 2009

  • 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,, 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.

    Copyright Oded Nissan 2009The Directive

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Implicit Objects

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Error Handling

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Error Handling

    Copyright Oded Nissan 2009

  • Throwing an Exception A sample Error page: An Error Has Occurred! An Error Has Occurred 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 .

    Copyright Oded Nissan 2009Error Handling

    Copyright Oded Nissan 2009

  • 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

    Copyright Oded Nissan 2009Error Handling

    Copyright Oded Nissan 2009

  • We can configure an error page for all exception types that subclass Exception: java.lang.Exception /ErrorPage.jsp The same error page mechanism available for catching thrown exceptions can be applied to responses with undesired HTTP headers: HTTP Code Relative URL

    Copyright Oded Nissan 2009Error Handling

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Java Beans

    Copyright Oded Nissan 2009

  • public class ExampleBean implements java.io.Serializable { String value; public ExampleBean() { } public String getValue(){ return value; } public void setValue(String value){ this.value = value; } } Copyright Oded Nissan 2009Java Bean Example

    Copyright Oded Nissan 2009

  • 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: Copyright Oded Nissan 2009Java Beans

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Java Beans Scopes

    Copyright Oded Nissan 2009

  • 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: useBean Example The date/time is

    Copyright Oded Nissan 2009Java Beans

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Java Beans

    Copyright Oded Nissan 2009

  • The geProperty action is used to get bean values: 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.

    Copyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • The setProperty action is used to set values of a bean: 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:Copyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • useBean Example Hello , welcome to this web page! Copyright Oded Nissan 2009Example

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Initializing Beans

    Copyright Oded Nissan 2009

  • JSP pages are deployed like static web resources (HTML files, images etc.) into the web applications 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.Copyright Oded Nissan 2009JSP Deployment

    Copyright Oded Nissan 2009

  • 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 directive.Custom tags provide a clean alternative to heavy and reusable scriptlet code.Copyright Oded Nissan 2009Custom Tags

    Copyright Oded Nissan 2009

  • 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).

    Copyright Oded Nissan 2009Custom Tags

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009Custom Tags

    Copyright Oded Nissan 2009

  • ...

    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.

    Copyright Oded Nissan 2009Using a Custom Tag

    Copyright Oded Nissan 2009

  • ExerciseCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • The Java Standard Tag Library(JSTL)Copyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • 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. Copyright Oded Nissan 2009The Java Standard Tag Library (JSTL)

    Copyright Oded Nissan 2009

  • select * from PUBLIC.books where id = ? Copyright Oded Nissan 2009JSTL Example

    Copyright Oded Nissan 2009

  • http://java.sun.com/products/jsp/jstl/reference/docs/index.htmlhttp://onjava.com/pub/a/onjava/2002/03/13/jsp.htmlhttp://www.javaworld.com/javaworld/jw-02-2003/jw-0228-jstl.html

    Copyright Oded Nissan 2009External Resourses

    Copyright Oded Nissan 2009

  • Java Server FacesCopyright Oded Nissan 2009

    Copyright Oded Nissan 2009

  • 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.Copyright Oded Nissan 2009Java Server Faces Overview

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009Java Server Faces (JSF)

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009The MVC Pattern

    Copyright Oded Nissan 2009

  • Copyright Oded Nissan 2009The MVC Pattern

    Copyright Oded Nissan 2009

  • 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.

    Copyright Oded Nissan 2009The MVC Pattern

    Copyright Oded Nissan 2009

  • Discussion of the MVC pattern implementation.

    Copyright Oded Nissan 2009The MVC Pattern

    Copyright Oded Nissan 2009

  • What did we discuss ?OverviewWeb ApplicationsServletsJava Server PagesCustom TagsJSTLJSFMVC

    Copyright Oded Nissan 2009Summary

    Copyright Oded Nissan 2009