Java 2 1 Table of contents 2

– JSP Basics – Servlet Table of contents 3

JSP Basics – Introduction – JSP Directives – Scripting elements – Standard actions – Implicit objects – Scope – JSP design basics – Dispatcher approach JSP Basics - Introduction 4 – The goal of the Java Server Pages (JSP) specifications is to simplify the creation and management of dynamic web pages, by separating content and presentation. – JSP tags are used to insert JAVAcode into HTML pages. – It is an advanced version of Servlet Technology. – It is a Web based technology helps us to create dynamic and platform independent web pages. – In this, Java code can be inserted in HTML/ XML pages or both. – JSP is first converted into servlet by JSP container before processing the client’s request. JSP Basics - Introduction 5 – Sample JSP program <%@page import="java.util.Date"%> Current time is <%= new Date().toString()%>

– JSP to servlet JSP Basics - Introduction 6 – JSP tags fall into three categories 1. Directives 2. Scripting elements 3. Actions JSP Basics - Introduction 7 – Some general rules applicable to JSP pages 1. JSP tags are case sensitive. 2. Attribute values in tags always appear quoted. 3. Any whitespace within the body text of a document is not significant, but is preserved during translation into a servlet. 4. The character \ (backslash) can be used as an escape character in a tag. JSP Directives 8 – The directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. – A JSP affects the overall structure of the servlet class. It usually has the following form − <%@ directive attribute = "value" %> – Directives can have a number of attributes which we can list down as key-value pairs and separated by commas. – There are three types of directive tag − 1. The page directive 2. The include directive 3. The taglib directive JSP Directives 9 The page directive – The directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. – The page directive is used to define and manipulate a number of important page-dependent attributes that affect the whole JSP, and communicates these attributes to the JSP container. <% page ATTRIBUTE%> <%@ page attribute="value" %> JSP Directives 10 The page directive – Attributes of JSP page directive : Import <%@ page import="java.util.Date" %> Today is: <%= new Date() %> JSP Directives 11 The page directive – Attributes of JSP page directive : contentType <%@ page contentType=application/msword %> Today is: <%= new java.util.Date() %> JSP Directives 12 The page directive – Attributes of JSP page directive : info <%@ page info="composed by Sonoo Jaiswal" %> Today is: <%= new java.util.Date() %> JSP Directives 13 The include directive – Include directive instructs the container to include the content of the resource in the current JSP, by inserting it, inline, in the JSP in place of directive. <% include file=“FileName” %> <% if((request.getParameter("username").equals("qwerty")) && (request.getParameter("password").equals("123456"))) {%> <%}else{%> <%@include file="index.html"%> <% }%> JSP Directives 14 The taglib directive – The JSP API allow us to define custom JSP tags that look like HTML or XML tags and a tag is a set of user-defined tags that implement custom behavior. – The taglib directive declares that our JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in our JSP page. <%@ taglib uri="uri" prefix = "prefixOfTag" > – Here, 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. Scripting Elements 15 – JSP scripting elements allow java code variable or method declaration, scriptlets (arbitrary java code), and expressions to be inserted into our JSP page. – Declarations <%! int data=50; %> <%= "Value of the variable is:"+data %> Scripting Elements 16 – Scriptlets : block of java code that is executed during the request processing time. <% int num1=10; int num2=40; int num3 = num1+num2; out.println("Scriplet Number is " +num3); %> Scripting Elements 17 – Expressions: The code placed within JSP expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method. <%= java expression to be evaluated%> <% out.println("The expression number is "); %> <% int num1=10; int num2=10; int num3 = 20; %> <%= num1*num2+num3 %> Standard Actions 18 – Standard actions are tags that affect the runtime behaviour of the JSP and the response sent back to the client. – There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks. – The action tags are used to control the flow between pages and to use Java Bean. The JSP action tags are given below. Standard Actions 19 JSP Action tag Description jsp:forward forwards the request and response to another resource. jsp:include includes another resource. jsp:useBean creates or locates bean object. jsp:setProperty sets the value of property in bean object. jsp:getProperty prints the value of property of the bean. jsp:plugin embeds another components such as applet. jsp:param sets the parameter value. It is used in forward and include mostly. jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin. Implicit Objects 20 – JSP provides certain implicit objects, based on the servlet API. These objects are accessed using standard variables, and are automatically available for use in JSP without writing any extra code. – The implicit objects available in JSP are 1. request 2. response 3. pageContext 4. session 5. application 6. out 7. config 8. page Implicit Objects 21 The request object – The JSP request is an implicit object of type HttpServletRequest i.e. 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. – It can also be used to set, get and remove attributes from the jsp request scope. String num=request.getParameter("Number"); //Number from HTML page (index.html) // Multiplication table program Implicit Objects 22 The response object – In JSP, response is an implicit object of type HttpServletResponse. The instance of HttpServletResponse 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.

The pageContext object – The pageContext object provides a single point of access to many of the page attributes and is a convenient place to put shared data within the page. Implicit Objects 23 The session object – In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to set, get or remove attribute or to get session information.

The application object – The application object represents the servlet context, obtained from the servlet configuration object. – This object can be used to get initialization parameter from configuarationfile(web.xml).Itcanalsobeusedtoget,setorremove attribute from the application scope. Implicit Objects 24 The out object – Writes into the output stream of the client.

The config object – In JSP, config is an implicit object of type ServletConfig. This object can be used to get initialization parameter for a particular JSP page. The config object is created by the web container for each jsp page. – Generally, it is used to get initialization parameter from the web.xml file.

The page object – The page object is the instance of the page’s implementation servlet class that is processing the current request. Scope 25 Page: – ‘page’ scope means, the JSP object can be accessed only from within the same page where it was created. – JSP implicit objects out, exception, response, pageContext, config and page have ‘page’ scope. request: – A JSP object created using the ‘request’ scope can be accessed from any pages that serves that request. More than one page can serve a single request. session: – ‘session’ scope means, the JSP object is accessible from pages that belong to the same session from where it was created. application: – A JSP object created using the ‘application’ scope can be accessed from any pages across the application. The JSP object is bound to the application object. JSP Design Basics 26 – Our aim in web application design must be to separate logic and presentation. There are two approaches to JSP design: 1. Page-centric or client-server designs. 2. Dispatcher or n-tier designs JSP Design Basics 27 – Our aim in web application design must be to separate logic and presentation. There are two approaches to JSP design: JSP Design Basics 28 – This is a simple design to implement – The JSP author can generate pages easily – Two variants : 1. Page-View 2. Page-View with a Bean – Does not scale up very well to large web sites – Often results in a lot of Java code in the JSP – JSP authors must be Java programmers – Design is hard to see – Hard to maintain JSP Design Basics 29 Page-View JSP Design Basics 30 Page-View JSP Design Basics: The Dispatcher Approach 31 – A “dispatcher” accepts requests and routes them to the correct place. – Front-end JSP (or servlet) looks at a portion of the request, and then chooses the correct place to forward it. – This is more sophisticated than the page-centric : – More flexible and scalable – More overhead that is wasted with small applications – Three versions 1. Mediator-View 2. Mediator-Composite View 3. Service to Workers JSP Design Basics: The Dispatcher Approach32 Page-View JSP Design Basics: The Dispatcher Approach33 Page-View JSP Design Basics: The Dispatcher Approach34 Page-View JSP Design Basics: The Dispatcher Approach35 Page-View JSP Design Basics: The Dispatcher Approach36 Page-View JSP Design Basics: The Dispatcher Approach37 Page-View Table of contents 38

Servlets – Life cycle of servlet – Java Server Development Kit – Servlet API – javax.servlet.Package – javax.servlet.httpPackage – Handling HTTP request and responses – Using Cookies – Session tracking Life cycle of servlet 39 – A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet. – The servlet is initialized by calling the init( ) method. – The servlet calls service( ) method to process a client's request. – The servlet is terminated by calling the destroy( ) method. – Finally, servlet is garbage collected by the garbage collector of the JVM. Life cycle of servlet 40 The init( ) Method – The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. – The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started. – When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init( ) method simply creates or loads some data that will be used throughout the life of the servlet. – The init method definition looks like this − public void init() throws ServletException { // Initialization code... } Life cycle of servlet 41 The service( ) Method – The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service( ) method to handle requests coming from the client( browsers) and to write the formatted response back to the client. – Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service( ) method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. – Here is the signature of this method − public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { } DoGet DoPost In doGet Method the parameters are In doPost, parameters are sent in appended42 to the URL and sent separate line in the body along with header information

Maximum size of data that can be There is no maximum size for data sent using doget is 240 bytes

Parameters are not encrypted Parameters are encrypted doGet method generally is used to doPost is generally used to update query or to get some information or post some information to the from the server server doGet is faster if we set the doPost is slower compared to doGet response content length since the since doPost does not write the same connection is used. Thus content length increasing the performance Life cycle of servlet 43 The service( ) Method The doGet() Method – A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet( ) method. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } The doPost() Method – A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost( ) method. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } Life cycle of servlet 44 The destroy( ) Method – The destroy( ) method is called only once at the end of the life cycle of a servlet. This method gives our servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such clean- up activities.

– After the destroy() method is called, the servlet object is marked for garbage collection. – The destroy method definition looks like this − public void destroy( ) { // Finalization code... } Servlet API javax.servlet Package 45 – The javax.servlet and javax.servlet.http packages contain the classes and interfaces that are required to build servlets. The javax.servlet Package – The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. Servlet API javax.servlet Package 46 The Servlet Interface – All servlets must implement the Servlet interface. – It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. – A method is also provided that allows a servlet to obtain any initialization parameters. The ServletConfig Interface – The ServletConfig allows a servlet to obtain configuration data when it is loaded. The ServletContext Interface – The ServletContext interface is implemented by the server. It enables servlets to obtain information about their environment. Servlet API javax.servlet Package 47 The ServletRequest Interface – The ServletRequest enables a servlet to obtain information about a client request. The ServletResponse Interface – The ServletResponse enables a servlet to formulate a response for a client. Servlet API javax.servlet Package 48 The javax.servlet Package – The following are the core classes that are provided in the javax.servlet package. Servlet API javax.servlet.http Package 49 The javax.servlet.http Package – The javax.servlet.http package contains a number of interfaces and classes that establish the framework in which servlets operate. Servlet API javax.servlet.http Package 50 The javax.servlet.http Package Handling HTTP request and responses 51 – The HttpServlet class provides specialized methods that handle the various types of HTTP requests. – A servlet developer typically overrides doDelete(),doGet(), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). Using Cookies 52 – The Cookie class encapsulates a cookie. – A cookie is stored on a client and contains state information. – Cookies are valuable for tracking user activities. – A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface. – The data for that cookie is then included in the header of the HTTP response that is sent to the browser. Session tracking 53 – HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. – A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings. – It is important to note that session state is shared among all the servlets that are associated with a particular client. Table of contents 54

– Introduction to Java Beans – Advantages of Java Beans – Bean Developer Kit (BDK) – JAR Files – Introspection – Using Bound Properties – BeanInfo Interface – Constrained Properties – Persistence – Customizers – The Java Beans API Introduction to Java Beans 55 – JavaBeans are reusable software components for Java. – Practically, they are classes written in the Java conforming to a particular convention. – They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. – A JavaBean is a Java Object that is serializable,hasazero- argument constructor, and allows access to properties using getter and setter methods. Introduction to Java Beans 56 // Java program to illustrate the // structure of JavaBean class public class TestBean { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } Advantages of Java Beans 57 – A Bean obtains all the benefits of Java’s “write-once, run- anywhere” paradigm. – The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled. – A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. – Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. – The configuration settings of a Bean can be saved in persistent storage and restored at a later time. – A Bean may register to receive events from other objects and can generate events that are sent to other objects. Bean Developer Kit (BDK) 58 – The Bean Developer Kit (BDK), available from the JavaSoft site, is a simple example of a tool that enables us to create, configure, and connect a set of Beans. JAR Files 59 – Tools such as the BDK expect Beans to be packaged within JAR (Java Archive) files. – A JAR file allows to efficiently deploy a set of classes and their associated resources. – For example, a developer may build a multimedia application that uses various sound and image files. A set of Beans can control how and when this information is presented. All of these pieces can be placed into one JAR file. – JAR technology makes it much easier to deliver and install software. Also, the elements in a JAR file are compressed, which makes downloading a JAR file much faster than separately downloading several uncompressed files. Digital signatures may also be associated with the individual elements in a JAR file. – The package java.util.zip contains classes that read and write JAR files. JAR Files 60 Manifest Files – A developer must provide a manifest file to indicate which of the components in a JAR file are Java Beans. – A manifest file may reference several .class files. If a .class file is a Java Bean, its entry must be immediately followed by the line “Java-Bean: True”. Name: sunw/demo/slides/slide0.gif Name: sunw/demo/slides/slide1.gif Name: sunw/demo/slides/slide2.gif Name: sunw/demo/slides/slide3.gif Name: sunw/demo/slides/Slides.class Java-Bean: True JAR Files 61 The JAR Utility – A utility is used to generate a JAR file. Its syntax is shown here: jar options files JAR Files 62 JAR Files 63 Creating a JAR File – The following command creates a JAR file named Xyz.jar that contains all of the .class in the current directory: jar cf Xyz.jar *.class

Tabulating the Contents of a JAR File – The following command lists the contents of Xyz.jar: jar tf Xyz.jar

Extracting Files from a JAR File – The following command extracts the contents of Xyz.jar and places those files in the current directory: jar xf Xyz.jar JAR Files 64 Updating an Existing JAR File – The following command adds the file file1.class to Xyz.jar: jar -uf Xyz.jar file1.class Recursing Directories – The following command adds all files below directoryX to Xyz.jar: jar -uf Xyz.jar - directoryX * Introspection 65 – Introspection is the process of analyzing a Bean to determine its capabilities. – This is an essential feature of the Java Beans API, because it allows an application builder tool to present information about a component to a software designer. – Without introspection, the Java Beans technology could not operate. Introspection 66 – There are two ways in which the developer of a Bean can indicate which of its properties, events, and methods should be exposed by an application builder tool. – With the first method, simple naming conventions are used. – These allow the introspection mechanisms to infer information about a Bean. – In the second way, an additional class is provided that explicitly supplies this information. – The first approach is examined here. Introspection 67 Design Patterns for Properties – A property is a subset of a Bean’s state. The values assigned to the properties determine the behavior and appearance of that component. – Simple Properties public Type getN( ); public void setN(Type arg); – Boolean Properties public boolean isN( ); public boolean getN( ); public void setN(boolean value); – Where N is the name of the property: Introspection 68 Design Patterns for Properties – Indexed Properties public T getN(int index); public void setN(int index, T value); public T[ ] getN( ); public void setN(T values[ ]); – Where N is the name of the property and T is its type: Introspection 69 Design Patterns for Events – Beans can generate events and send them to other objects. These can be identified by the following design patterns, where T is the type of the event: public void addTListener(TListener eventListener); // The first pattern indicates that a Bean can multicast an event to multiple listeners. public void addTListener(TListener eventListener) throws TooManyListeners; // The second pattern indicates that a Bean can unicast an event to only one listener. public void removeTListener(TListener eventListener); Developing a Simple Bean 70 1. Create a directory for the new Bean. 2. Create the Java source file(s). 3. Compile the source file(s). 4. Create a manifest file. 5. Generate a JAR file. 6. Start the BDK. 7. Test. Developing a Simple Bean 71 Step 1 - Create a library – In netbeans, file->new project – for category choose 'java' – for project choose 'java class library' – Then choose an appropriate location and name for your library. I chose grlib1 for the name.

Step 2 - create a class – Colors.java Developing a Simple Bean 72 Step3-Fixmanifesttoshowthisisabeanlibrary – First get to the files tab of your project. – Open build-impl.xml file which inside nbproject. – Find Some code is already here – Add inside tag. Ie – Build the project. Developing a Simple Bean 73 Step 4 – Test it – Open an existing file (Checkbox program). – In menu system do: tools -> palette -> Swing/AWT Components – Add From Project... (Or Add JAR and select the path of the JAR file) – Select the project, select the available component Next, select Bean finish. – Now we should see our bean in the pallette near the bottom in the Beans section. – Now its ready to use. We can drag it on to the Jframe to use it. BeanInfo Interface 74 – BeanInfo is an interface implemented by a class that provides explicit information about a Bean. – It is used to describe one or more feature sets of a Bean, including its properties, methods, and events. PropertyDescriptor[ ] getPropertyDescriptors( ) EventSetDescriptor[ ] getEventSetDescriptors( ) MethodDescriptor[ ] getMethodDescriptors( ) – They return arrays of objects that provide information about the properties, events, and methods of a Bean. By implementing these methods, a developer can designate exactly what is presented to a user. BeanInfo Interface 75 – The classes PropertyDescriptor, EventSetDescriptor,and MethodDescriptor are defined within the java.beans package, and they describe the indicated elements. – By implementing these methods, a developer can designate exactly what is presented to a user, bypassing introspection based on design patterns. Bound and Constrained Properties 76 Bound Properties – A Bean that has a bound property generates an event when the property is changed. – The event is of type PropertyChangeEvent and is sent to objects that previously registered an interest in receiving such notifications. Bound and Constrained Properties 77 Constrained Properties – A Bean that has a constrained property generates an event when an attempt is made to change its value. – It also generates an event of type PropertyChangeEvent.Ittoo is sent to objects that previously registered an interest in receiving such notifications. However, those other objects have the ability to veto the proposed change by throwing a PropertyVetoException. This capability allows a Bean to operate differently according to its run-time environment. A class that handles this event must implement the VetoableChangeListener interface. Customizers 78 – A Bean developer can provide a customizer that helps another developer configure the Bean. A customizer can provide a step- by-step guide through the process that must be followed to use the component in a specific context. Online documentation can also be provided. A Bean developer has great flexibility to develop a customizer that can differentiate his or her product in the marketplace. The Java Beans API 79 – The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package. The Java Beans API 80 The Java Beans API 81 The Java Beans API 82 PropertyDescriptor – The PropertyDescriptor class describes a Bean property. It supports several methods that manage and describe properties. – For example, we can determine if a property is bound by calling isBound( ). – To determine if a property is constrained, call isConstrained( ). – We can obtain the name of property by calling getName( ). The Java Beans API 83 EventSetDescriptor – The EventSetDescriptor class represents a Bean event. It supports several methods that obtain the methods that a Bean uses to add or remove event listeners, and to otherwise manage events. – For example, to obtain the method used to add listeners, call getAddListenerMethod( ). – To obtain the method used to remove listeners, call getRemoveListenerMethod( ). – To obtain the type of a listener, call getListenerType( ). – We can obtain the name of an event by calling getName( ). The Java Beans API 84 MethodDescriptor – The MethodDescriptor class represents a Bean method. To obtain the name of the method, call getName( ). – We can obtain information about the method by calling getMethod( ).