Você está na página 1de 130

Java Servlet

Servlets Introduction to Web Application / Web Site A web site consists of collection of web pages. The information contained in each page is called as hypertext. The protocol that is used to access this information is called as Hyper Text Transfer Protocol (HTTP). It is based on TCP-IP. A client (using browser such as internet explorer/Firefox etc) accesses this information using URLs. A URL is Uniform Resource Locator and it is used to uniquely identify an internet resource. It has following format Protocol://hostname:port/filepath e.g. http://www.somewhere.com:10456/index.jsp Protocol: http/smtp/pop3/ftp/file Hostname:
downloading

www.somename.com

Server

DNS

ISP

Client

where
www.somename.com

168.25.12.45:portno Protocol can be ftp/http/telnet etc and it identifies the type of service, Hostname is a name of machine or IP address (32-bit) which represents the server on which the service is running, [e.g. 168.25.12.45] Port is an (16-bit) integer that maps requests coming from network to specific application on the host. A host can run many services. Since, physically there is only one connection to the computer; ports allow us to have multiple logical connections, each for a specific type of service through which the specific packets will be delivered to the particular process.

File path is a name of file with directory listing which a user wants to access.
File Path

For example http://www.yahoo:1247/india/index.html

Protocol

Host Server Name

Port number

When a user types a URL in a browser, the request is passed through the network in the form of packets to the particular server. If the server process is on, it will process the request that contains the name of the file requested by the user. If it is an HTML file, then the contents of the file are transferred from server to the client machine where it is interpreted by browser.
Downloading Request Response Request Response Request Response Web-Server IIS-Internet Information services Apache Tomcat JWS-Java Web Server Client3 Client2

Client1

Web Server Static Page Dynamic Page

http://www.somename.com 202.16.78.2 [ip-address] SERVER


Dynamic Pages 1.Asp 2.PHP 3.ASP.NET 4.Servlet 5.JSP

Pure HTML Pages

Need of Server Side Technologies The information contained in web pages can be written using a language called Hyper Text Markup Language (HTML). This language just provides the facility to show data in various forms, tables, images etc. But many times, server is required to process information submitted by the client. HTML is not powerful enough to provide facilities such as arithmetic calculations, database connectivity, file handling etc. provided by other languages. Hence we need a programming technology that can be used on web servers for processing clients information. For example, CGI, ASP, ASP Dot Net, Servlets, JSP, PHP etc are among few technologies which are used for server-side programming. The programs written in any of these technologies are executed by specific web servers (Tomcat/Apache/IIS/PWS/JWS etc). HTML pages always give same output to all users thats why they are used for static content generation. But programs can offer different output to different users so they are used for dynamic content generation. Responsibilities of Server side Technologies A web server is generally kept on all the time (except at the time of maintenance) as a web site can be accessed any time in a day. There are various issues as far as server-side program loading and execution is concerned 1. Lifetime of programs Generally a program is loaded for execution in memory and after its execution, removed from the memory. But when it is run on a web server, whether the program should be kept in memory expecting that new requests will be coming for the same. 2. Concurrent execution Multiple clients may request execution of the same program simultaneously. So whether to load the program once or for every client separately. 3. Input/output generation The program running on the server side will need to identify the information of each client separately and it needs to generate a separate output for each client. Sometimes the output is required to be buffered. 4. Inter-Program communication Sometimes a program may need to communicate to other programs running on the server. 5. Configuration Information A program may require information stored in configuration files so that it can behave differently without changing the actual code of the program.

And there can be many more. Thus, a programmer who is writing a server-side program will be required to write code for all above mentioned services. But it would be better if the web server itself provides these services.

Introduction to Servlets Servlets (Server Side Applets) is a Java-based technology used for serverside programming in developing web applications. Advantages of servlets are as follows 1. PortabilitySince it is based on Java, servlets are platform independent. 2. Performance Servlets are loaded only once in memory unlike ASP. So they take less memory. Only single instance of servlet object is used by all clients. So they take less memory. 3. Compiled ASP is interpreted for every execution. Since servlet is a java class, it is compiled to give a .class file. Thus it need not be compiled for every client request. 4. Security Since java has in-built security managers, servlets are secure. They are also protected by web sever. 5. Use of all features of Java Packages: Since it is based on java language, it can make use of all features of java such as IO, jdbc, file handling etc. Servlet Life Cycle (Lifecycle Service) Servlets are mainly on an interface called as Servlet. This interface contains mainly three methods init, service and destroy that control the life cycle of every servlet. init method is called when the servlet is first loaded in the memory. service method is called for every client. destroy method is called only once, when the servlet is removed from the memory.

There are two main implementations GenericServlet and HttpServlet. Servlet | Generic Servlet Http Servlet | | Myservlet 1 Myservlet2

to

this

interface

Generic Servlet: A GenericServlet is used for writing protocol independent servlets. That means, a servlet should be executed using any other protocol such as FTP. But such type of servlets are not used to that extent. HttpServlet: This class is HttpServlet that makes use of HTTP and this is used more often. When we have to write servlet programs, we write subclass of either GenericServlet or HttpServlet. This is similar to the concept of interface, its adapter class and subclass of adapter class. public class myservlet1 extends GenericServlet { public void init() { //servlet initialization codes goes here } public void service (ServletRequest request, ServletResponse response) { //servlet service codes goes here } public void destroy() { //servlet destroy methods codes goes here }

} The servlet objects are managed by servlet-container whose role is to provide all the services to servlets as mentioned above. Our servlets act like components which are managed by servlet container(Component-Container

Model). Servlets will not contain any constructor as the object is created by container and not by the user.

Using Tomcat 5.x (Compatible with JDK1.6) This is a web-server that we have to use to execute servlets. directories such as It contains

1. bin it contains two main files startup.bat and shutdown.bat which are run to start or stop the web server resply. 2. lib this directory contains a file called servlet.jar. It contains the packages and classes that are used for servlets. The javax.servlet and javax.servlet.http are not part of JDK. They are generally present in web servers. To use them, you need to set the classpath before compiling servlet programs. Set classpath= C:\Program Files\Apache Group\Tomcat5.x\common\lib\servlet-api.jar; Or create environment variable as classpath 3. webapps - it contains our applications stored in separate directories. In webapps, specific directories should be created. The hierarchy is as follows webapps <some folder name> .html / .jsp files WEB-INF web.xml file (Deployement descriptor) classes .class files

The html/jsp/class files should exist in specific directories. HTML files are run by using http://localhost :8080/<Folder name>/filename.html. Servlets are executed by http://localhost :8080/<Folder name>/servlet/filename where servlet in URL specifies command to execute a servlet. <folder name> can be replaced by any user-specific directory. Web.xml file is a special file that can be created in every directory. It is called as Deployment Descriptor. Generally executable files have same type of behavior because the code of such files cannot be changed. But we want that the files should have different behavior, then we need to have some other files containing information which should be used by executable programs. Such configuration files contain information such as literals representing filenames, database names, colors, menu names, co-ordinates etc. web.xml is one such file that is used by servlets for dynamic behavior. Developers develop programs. Deployers write configuration files. Writing Servlet programs 1. s1.java import java.io.* ; import javax.servlet.* ; public class s1 extends GenericServlet { public void init(ServletConfig sc) { System.out.pritnln(The servlet has been loaded); } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException out { res.setContentType("text/html"); OUTPUTSTREAM PrintWriter out=res.getWriter(); <html> out.println("<html>"); <head> <title> </title> out.println("<head>"); <body> out.println("<title>"); <h1>Hello Servlet </h1> </body> WEBSERVER out.println("Understanding Servlet"); </html> PURE HTML out.println("</title>"); s1.java out.println("<body>"); out.println("Hello Servlet"); out.println("</body>"); out.println("</html>");

out.close(); } public void destroy( ) { System.out.println(The servlet is about to be destroyed); } } To write servlet programs, you need import classes from javax.servlet package (for GenericServlet). The above programs contains implementations to init, service as well as destroy methods. However init and destroy are optional. Generally, only one servlet object is created in memory and it is shared by all clients. Init method is executed only once, when the servlet is first loaded into memory. It accepts one parameter of ServletConfig type which is created by servlet container for specific servlet that contains configuration parameters. Destroy method is also called only once when the servlet is removed from the memory. This is decision is upto servlet container that when a servlet should be removed from the memory(for example, when no requests comes in 10 mins). Service method is executed by each and every client. Servlet Container creates two objects request and response for every client. Thus if there are 1000 clients accessing a servlet then there will be 1000 request-response object pairs. Request object contains information submitted by the client and response object stores information that should go to client. Writing to client, can be done in a convenient manner by using PrintWriter object that can be obtained from response object. It can accept data of different types such as string, int, float etc. and it also has an internal buffering mechanism. Content-type sets the MIME(Multi-purpose Internet Mail Extension) type of data. Text/html means that the data bytes sent by the server represent text but browser should read it as html(text/plain will give normal text output). After all data is written, out.close will actually finalize the data buffer and send it to the client. If you want to transfer data to the client, before closing the stream you can call out.flush( ) method. 2. s2.html <html> <form method=get action=http://localhost:8080/servlet/s2> Name : <input type=text name=t1>

Psswd : <input type=password name=t2> <input type=submit value=Login> </form> </html> s2.java import java.io.* ; import javax.servlet.* ; public class s2 extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); out.println(Hello); String user = req.getParameter(t1); String pass = req.getParameter(t2); if(pass.equals(admin)) out.println(user); else out.println(user); out.close( ); } } About Get and Post Request There are two types of requests using which data is sent to the server Get request and Post request. In get request, the data is appended to URL in the form of key-value pairs. But there is a limit on the length of URL(max 255 chars). Also this is an insecure way to transmit data as anybody will be able to read it in the address bar. For example http://localhost:8080/kamlakar/servlet/k1?t1=rahul&t2=admin The other method is post, in which data is sent through HTTP body. It has no limitation as far as the amount of data is concerned. It is secure way to transfer data.

Writing HttpServlet When we extend from HttpServlet, we need to override either doGet or doPost method based on type of request used in HTML.

h1.java import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* public class h1 extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); out.println(Hello); out.close( ); } } HttpServlet service( ...) method implementation contains a code to check the type of request and to call doGet or doPost method which are defined in it. When we extend from HttpServlet, we need to override either doGet or doPost method. It is important that one should check what is the type of request ( get or post) used in the html file. If method=get or method=post attributes defined in HTML file dont match with doGet or doPost, then you will get an error. To avoid such type of errors, one can use the following approach

h2.java import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* public class h2 extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); out.println(Hello); out.close( ); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } } Reading different types of parameters Normally all types of parameters such as textfields, passwords, check box, radio buttons etc are read by req.getParameter(name) method except for multiple selection list box. It is read as a string array as follows

String degs [] = req.getParameterValues( degrees) ; for(int I=0; I< degs.length; I++) {

out.println(::: + degs[I] + :::); }

Setting & Reading Contextual & Configuration Parameters Servlet Container provides two types of configuration parameters, context level and configuration level. Context parameters are accessed by all servlets within an application whereas configuration parameters are for specific servlets. They are available using two classes ServletContext and ServletConfig. For this, you have to provide the parameters in web.xml file. A sample web.xml is as follows Web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <context-param> <param-name>country</param-name> <param-value>India</param-value> </context-param>

<servlet> <servlet-name> Delhi</servlet-name> <servlet-class>s1</servlet-class> <init-param>

<param-name> minister </param-name> <param-value>shila dixit</param-value> </init-param> </servlet>

<servlet> <servlet-name> Mumbai</servlet-name> <servlet-class>s2</servlet-class> <init-param> <param-name> min</param-name> <param-value> VilasRao</param-value> </init-param> </servlet> </web-app>

s1.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class s1 extends HttpServlet { String min = ;

public void init(ServletConfig sc) { min = sc.getInitParameter(minister); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); ServletContext sx = getServletContext( ); String c = sx.getInitParameter( country); out.println(Hello, I am + min + from + c); out.close( ); } }

s2.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class s2 extends HttpServlet { String min = ; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); ServletContext sx = getServletContext( ); String c = sx.getInitParameter( country); ServletConfig sc = getServletConfig( ) ; String min = sc.getInitParameter(min); out.println(Hello, I am + min + from + c); out.close( ); } }

Note : The servlets should be run using their names such as http://localhost:8080/kamlakar/servlet/Delhi

Using Redirection In the above servlets, the output was produced by writing HTML code in out.println() statements. This method may not work always. Suppose there is an HTML file that already exists in context directory whose contents should be sent to the client. Then one can use a method called sendRedirect (URL l) available with HttpServlet class. hredirect.java import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* public class hredirect extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse throws ServletException, IOException res)

{ res.setContentType(text/html); PrintWriter out = res.getWriter( ); String login = req.getParameter(t1); if(login.equals()) res.sendRedirect(http://localhost:8080/error.html); else { out.println(Welcome); out.close( ); } }

} Inter-servlet Communication Sometimes servlets in an application require to communicate to each other or in other terms require to share data. Generally when two functions want to communicate to each other, then they can do it using two approaches (i) using global variables that are shared by both, (ii) message passing approach, in which one function passes parameters that can be used by other. Similar type of approach can be used in servlets.

I. Using ServletContext Since a single ServletContext that is created by servlet container for all servlets of an application, if we add some information in ServletContext, it can be accessed by all the servlets of an application. To store & retrieve information from ServletContext, we use two methods - (i) setAttribute(String key, Object o), (ii) Object getAttribute(String key). pairs. Objects are stored using key-value

ServletContext internally contains a HashTable. A hashtable stores collection of objects using a technique of hashing. SetAttribute function adds the object in servletcontext using a key. To retrieve the object, one needs to pass the same key to getAttribute function. However, appropriate type-casting is required to use the object. Thus objects added in ServletContext have application-level scope.

webapps rahul login.html WEB-INF

classes login.class info.class

login.html

<html> <form method=get action=http://localhost:8080/kamlakar/servlet/login> Name : <input type=text name=t1><br> Passwd : <input type=password name=t2> <input type=submit value=Submit> </form> </html>

login.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class login extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType(text/html); PrintWriter out = res.getWriter( ); String login = req.getParameter(t1); String passwd = req.getParameter(t2); if(passwd.equals(admin)) out.println(Hello); else out.println(Invalid login);

ServletContext sx = getServletContext( ) ; String count = (String) sx.getAttribute(count); if( count ==null) sx.setAttribute(count, 1); else { int i = Integer.parseInt(count); i ++; sx.setAttribute( count, +i ); } } }

info.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class info extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); ServletContext sx = getServletContext( ) ; String count = (String) sx.getAttribute(count); if( count ==null) out.println(0 logins so far); else out.println( count + number of logins so far); } }

II. Using Servlet-Chaining / Message Passing 1. What is Servlet-Chaining? or 2. How Message Passing is taking place in servlet? Give Example or 3. Explain use of RequestDispatcher method in servlet? In this method, first servlet can forward the request to second servlet or can include contents from by another servlet. This is different from redirection. In redirection, servlets cannot share information. But in this approach, servlets can share information. In this method, a servlet indirectly calls service method of another servlet. Normally a servlet is accessed by client through browser. When request for the servlet, comes from client to web-server, it finds the servlet on the server, creates request-response object and passes that to the servlet. But when a servlet calls another servlet, there are two problems 1. How to get reference of another servlet object in the first servlet object, 2. What about request-response objects that are required as parameters of service method These two problems are solved as follows (i) To gain reference of another servlet, servlet container provides a class called RequestDispatcher whose job is to refer to the target servlet, (ii) The calling servlet can pass its own request-response objects to another servlet.
Request Object 1 2 If condition is true Request Dispatcher object forward 3

Login.html

Login.java

welcome.java If condition is false Request Dispatcher object include 4

error.java

login.java import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* public class login extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String login = req.getParameter(t1); String passwd = req.getParameter(t2); if(passwd.equals(admin)) { RequestDispatcher rd =req.getRequestDispathcer(welcome); rd.forward(req,res); } else { res.setContentType(text/html); PrintWriter out = res.getWriter( ); RequestDispatcher rd = req.getRequestDispathcer(error); rd.include(req,res); out.close( ); } } } welcome.java

import java.io.* ; import javax.servlet.* ;

import javax.servlet.http.* public class welcome extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); String user = req.getParameter(t1); out.println(Hello, + user); out.close( ); } } error.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class error extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( );

out.println(Error in login); } }

Note :

1. Generally, a servlet which forwards clients request to another servlet does not write anything to PrintWriter. 2. 3. A servlet whose contents are included, does not close the PrintWriter. You can add objects in request object similar to ServletContext. But

objects that are added in request objects can be accessed only by servlets in the chain and not in those servlets that are in the same application. req.setAttribute(String key,Object value) and Object req.getAttribute(String key)

Generally, the information which is not passed by client through HTML, can be stored in request object.

login.html

<html> <form method=get action=http://localhost:8080/kamlakar/servlet/login> First Name : <input type=text name=t1><br> Last Name : <input type=text name=t2> <input type=submit value=Submit>

</form> </html>

login.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class login extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

String fname = req.getParameter(t1); String lname = req.getParameter(t2);

req.setAttribute(fullname,fname + + lname); RequestDispatcher rd = req.getRequestDispathcer(welcome); rd.forward(req,res); } }

welcome.java

import java.io.* ; import javax.servlet.* ; import javax.servlet.http.*

public class welcome extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res.getWriter( ); String fullname = (String) req.getAttribute(fullname); out.println(Hello, + fullname); out.close( ); } }

Maintaining State of the client 1. Explain How Web page is maintain state of the client in Java 2. Explain Cookies or Write short notes on cookies and Give Example 3. Explain Session Tracking? Or different type session tracking Many times, a site consists of multiple web pages which call multiple programs. During this process, information generated by various pages are required to be maintained through multiple requests. So data has to be stored in the memory. For example, an online exam contains multiple random questions. A user may get questions through HTML files one by one and he/she may give answers which go to servlets for evaluation. During this process, the score of every user must be calculated and maintained until the last question is answered. HTTP is a stateless protocol. It means that every request coming to servlet is independent of the previous one. So for a servlet, its difficult to know whether the request is coming from the same client or not. So far, we have studied two techniques to share information one using ServletContext and the other by using RequestDispatcher. ServletContexts purpose is to store data for all servlets and not of specific clients. Using request dispatcher, one can add data in request object and maintain data specific of clients. But request object exists as long as the control is in service method (or on server side). Once the control is transferred from servlet to clients browser, request object is destroyed. Two techniques are used for this purpose Cookies and Sessions. Cookies Cookies are used to maintain information about client. These are used on client side. Cookie class is used to create a cookie. Cookies are valuable for storing user activities. Cookies can be used to store users name, address etc. A servlet can write a cookie a cookie to a users machine via the addCookie ( ) method of response object. The data is included at the header of response. The names and values of cookies are stored on client side. Some attributes of cookies are name, value, expiration date, domain and path. Expiration time is used to denote time after which the cookie should be deleted. By default, the cookie is deleted when browser session ends.

Otherwise it is stored in a file. Domain and path determine when it can be included in the header of HttpRequest.

C
Name: BBB
Paaword: 1234

C
Name: AAA
Paaword: 1234

Yahoo.com

Expired date

Response.addcokies(Cookie c)

Yahoo.com

Expired date
path

Request

Request

Client 1

Client 3

Server Request www,yahoo.com Client 2 C


Name: CCC
Paaword: 1234

Request Client 4 C
Name:DDD
Paaword: 1234

Yahoo.com

Yahoo.com

Expired date

Expired date

potterclub.html <html> <form method=get action=http://localhost:8080/milind/servlet/potterfan> <h1> Harry Potter's Fan Club<br> <h3> Kindly register....<br> Name : <input type=text name=t1> <br> Password : <input type=password name=t2> <br> Email-Id : <input type=text name=t3> <br> <input type=submit value="Be Gryffindor"> </form> </html>

potterfan.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class potterfan extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException { String name = req.getParameter("t1"); String pass = req.getParameter("t2"); String email = req.getParameter("t3");

Cookie c = new Cookie("potterfan",name); c.setMaxAge(1000); res.addCookie(c);

res.setContentType("text/html"); PrintWriter out = res.getWriter();

out.println("Hello, " + name); out.println("Click on any of the link below..."); out.println("<br><a href=http://localhost:8080/milind/servlet/potter1> Harry Potter & The Socer's Stone </a>"); out.println("<br> <a href=http://localhost:8080/milind/servlet/potter2> Harry Potter & The Prizoner of Azkaban </a>"); out.close(); } }

potter.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class potter extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); Cookie c[] = req.getCookies();
Name PotterFan PotterFan PotteFan C value Sukhiram dhaniram dukhiram

for(int i=0; i<c.length; i++) { String name = c[i].getName(); if(name.equals("potterfan")) { out.println("Hello, " + c[i].getValue()); out.println("<br> Click on any of the link below..."); out.println("<br> <a href=http://localhost:8080/milind/servlet/potter1>Harry Potter & The Socer's Stone </a>"); out.println("<br> <a href=http://localhost:8080/milind/servlet/potter2>Harry Potter & The Prizoner of

Azkaban</a>"); out.close(); return; } } res.sendRedirect("http://localhost:8080/milind/potterclub.html"); } }

Sessions

Bill

124398594 Mr X -Enter Session ID 124398594 Product 2 124398594 1001 124398594 1001 2001 Mr X -select Product 1

1001

2001

Mr X -Select Product 1

Session tracking gives the servlets and other server-side applications the ability to keep track of a user information as he moves through various pages of the site. To identify clients, we can use IP address but it may happen that two different clients from the same machine can send the request or it can be the address of proxy server through which multiple clients are connected. The other way is to use clients login id. But login-ids may be shared and it may happen that two clients from different locations login to the server with same id. So the best way is to identify request. To identify every request separately, servlet container creates a session object for every request and assigns a unique session-id.

Fname.html

Fname: ABC

<form method=get action=http://localhost:8080/milind/servlet/fname> Fname : <input type=text name=t1> <br> <input type=submit value=Fname> </form>

lname:XYZ

lname.html

<form method=get action=http://localhost:8080/milind/servlet/lname> Lname : <input type=text name=t1> <br> <input type=submit value=Lname> </form>

fname.java

Fname: ABC

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class fname extends HttpServlet {

fname ABC public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException { HttpSession hs = req.getSession(true);

hs 12433568789

fname ABC

System.out.println("Session created : "+ hs.getId()); String fname = req.getParameter("t1"); hs.setAttribute("fname",fname); res.sendRedirect("http://localhost:8080/milind/lname.html");

} }

lname.java

lname 12433568789

xyz ABC xyz

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

12433568789

ABC

public class lname extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession hs = req.getSession(false);

if(hs!=null) { String fname = (String)hs.getAttribute("fname"); String lname = req.getParameter("t1");

PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("Hello, " + fname + " " + lname);

} else { res.sendRedirect("http://localhost:8080/milind/fname.html"); } } }

Synchronization in Servlets Generally, a single instance of servlet is created which processes multiple clients by calling service method of servlet object for every client using threads. But this may create problems if multiple clients need to share a single resource in a servlet. Synchronization is technique to provide controlled access to a shared resource among multiple simultaneous requests. It makes sure that only one request uses the resource at a time. If there is another request for the same resource, then it will be kept in wait state. 1. Service method of the servlet is executed for every client, if variables are declared in service, then they will be created for every client. So they dont need synchronization. 2. But if there is a class variable, then there will be only one copy of it, since there is only one servlet object. If the variable is a read-only variable then again synchronization is not necessary. But if the variable is required to be changed by all the threads, then synchronization is required. For example
multi.html * * * * * * multi.java

Number:

Submit

multi.html <form method=get action=http://localhost:8080/servlet/multi> Number : </form> I Non synchronized code multi.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet { String num; // Shared Resource int n; // Shared Resource public void init(ServletConfig sc) { num = ""; n = 0; } public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); num = req.getParameter("t1"); n = Integer.parseInt(num); for(int i=1; i <= 10; i++) { out.println( "<br>" + n + " * " + i + " = " + (n*i) ); for (long l=1; l<=100000000; l++); } out.close(); <input type=text name=t1><br> <input type=submit value=Table>

} II. Using local variables instead of class variables multi.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet { String num; int n; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); String num = req.getParameter("t1"); // Non-shared Resource int n = Integer.parseInt(num); // Non-Shared Resource for(int i=1; i <= 10; i++) { out.println( "<br>" + n + " * " + i + " = " + (n*i) ); for(long l=1; l<=100000000; l++); } out.close();

} }

In the above example, we have declared local variables instead of class variables. Since they are created for every client when service functions is called, synchronization is not necessary since the variables are not shared. III. Using synchronized methods multi.java import java.io.*;

import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet { Static String num; // Shared Resource Static int n; // Shared Resource public void init(ServletConfig sc) { num = ""; n = 0; } public void synchronized doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); num = req.getParameter("t1"); n = Integer.parseInt(num); for(int i=1; i <= 10; i++) { out.println( "<br>" + n + " * " + i + " = " + (n*i) ); for(long l=1; l<=100000000; l++); } out.close(); } }

synchronized keyword acts like a lock on a shared resource. When one thread acquires a lock on the shared resource, the other thread cannot access the resource unless the first thread releases the lock. It works on the concept of monitor or semaphore. In java, all objects java their own implicit monitor associated with them. To enter an objects monitor, we need to call a synchronized method. While a thread is inside synchronized method, all other threads that try to call it ( or any other synchronized method) on the same instance have to wait. Here we have declared doGet method as a synchronized method. IV. Using synchronized blocks multi.java import java.io.*;

import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet { String num; // Shared Resource int n; // Shared Resource public void init(ServletConfig sc) { num = ""; n = 0; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); synchronized(this) { num = req.getParameter("t1"); n = Integer.parseInt(num); for(int i=1; i <= 10; i++) { out.println( "<br>" + n + " * " + i + " = " + (n*i) ); for(long l=1; l<=100000000; l++); } } out.close( ); } } Synchronizing whole methods can seriously affect the performance. Because if we synchronize doGet method, then all other clients sending requests to server at the same time will have to wait to acquire the lock. Actually we need not synchronize all statements of the method. Only those statements where the value of shared resource is changed are enough to be synchronized. So instead of using synchronized methods, its better to use synchronized block. Synchronized blocks need an object, that you want to synchronize. Thus, using this approach, you can also synchronize access to methods, if the original methods cannot be declared as synchronized.

V. Using SingleThreadModel (Multiple instances of servlet class) multi.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class multi extends HttpServlet implements SingleThreadModel { String num; // Shared Resource int n; // Shared Resource int s; public void init(ServletConfig sc) { System.out.println(In init + (++s) ); num = ""; n = 0; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); num = req.getParameter("t1"); n = Integer.parseInt(num); for(int i=1; i <= 10; i++) { out.println( "<br>" + n + " * " + i + " = " + (n*i) ); for(long l=1; l<=100000000; l++);

} }

} out.close();

This is an all-together different approach. It ensures that servlets handle only one request at a time. This interface has no methods. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each

new request to a free servlet. If a servlet implements this interface, the servlet will be thread safe. However, this interface does not prevent synchronization problems that result from servlets accessing shared resources such as static class variables or classes outside the scope of the servlet. Note that SingleThreadModel does not contain any method.

JSP Introduction A web application consists of number of web pages. These web pages are generally developed using HTML. But pages developed using HTML produce static output or they have passive behavior. But at times you want to give different output to users by changing only a small part of the page. For example, if you want to display date and time or hit-count require a very small change in web page. To provide dynamic behavior to it, small programs can be included in HTML. This makes web pages to give different output for different users. Thus the behavior of the page becomes active. Java Server Pages (JSP) is a Java-based technology that simplifies the process of developing dynamic web-sites using JSP, web designers & developer can quickly incorporate dynamic elements into web pages using embedded Java & markup tags. The tags allow the user to present data & java object (Applet/JDBC/Java bean/servlet etc) allow storing business logic. JSP specification is a standard extension defined on top of the servlet API. JSPs are text files with .jsp extension, which includes HTML/XML tags along with embedded java code.

Advantage Of JSP Technology 1. Portability Since it is based on Java, JSP technology is platform independent. To run .jsp files, we need a JSP engine (programs used to run .jsp files). This engine can be built for different type of web-servers to make them execute jsp files. 2. Reuse of Components & Tag Libraries

JSP technology emphasizes the use of reusable component such as Java Bean Components, Enterprise Java Bean Components etc. Data is the main reason of dynamic contents. The components may contain the code to obtain the data from databases or text files thus offering different contents to JSP files.

It supports different type of markup languages such as HTML/DHTML/XML. JSP also supports user-defined tags. For user-defined tags, the control is transferred to classes that contain the code, which should be executed. Any type of code such as JDBC, File Handling etc can be included in these classes. Thus a JSP page developer need not have considerable knowledge of Java. 3. Separation of static & Dynamic Content

Using HTML pages, we can send only static contents to web clients. If we use servlets, then the entire HTML code is required to be written in println statement, which is tedious. It also makes the entire page to be dynamic. JSP allows you to include dynamic content into the static contents separating the two from each other. The static contents are provided using HTML tags and dynamic contents are generated using scriptlets, user-defined tags etc. It also follows popular MVC (Model-View-Control) Design Pattern. 4. Suitable for N-Tier Architecture

Because of features such as, platform-independence, support for different types of servers(web servers, database servers etc), markup languages, reuse of objects in the form of components etc. it is best suited for N-Tier architecture.

5.

Performance

JSP pages are automatically compiled before execution. So it frees the job of programmer to explicitly compile the program. After compilation, the page is kept in memory for certain duration to serve for next requests. Thus the compilation activity is not done for every request(unless there are modifications in the page).

What is difference between ASP and JSP ASP VS JSP Category Platform Support ASP Windows only Interpreted request for JSP All java enabled platforms every Compiled once again and again executed

Type Memory requirements Web Server Support Reusable objects Scripting Languages

Loaded for each request IIS, PWS COM / DCOM VBScript, Java script

Loaded only once in memory Any web server Apache, Netscape, IIS etc Java Beans, Servlets, EJB Java / Java script

Customizable tags Memory protection leak

Cannot use custom tag Extensible with custom tag libraries and is not libraries. extensible. No Yes

Write down difference between Servlet and JSP Servlets VS JSP

Servlets JSP 1. Servlets are less efficient in 1. JSP offers a clear separation of generating dynamic contents. static and dynamic contents.

2. Servlets files compiled by user.

must

be 2. JSP files are automatically compiled.

3. Developers need to have 3. Developers need not have significant knowledge of Java. significant knowledge of Java. 4. Management of beans is done 4. Management of beans is done using java code using tags. Form.html <html> <head><title> </title></head> <body> <form name=frm method=post action:http://localhost:8080/one.jsp> Enter the name <input type=text name=txtname> </form> </body> </html>

One.jsp <html> <body> Hello. <% String uname=request.getParameter(txtname); if(uname==null) uname=world; %> Hello, <%= uname %>! </body> </html> <% .%> JSP/Java codes(Scriplet) <%=%> variables request includes includes Http request object

Explain the JSP Execution? How JSP execute on client side? JSP Execution When a server receives a request for JSP file, the request is sent to the JSP engine. The JSP engine checks whether it already exists in memory or not. If it doesnt, then the engine compiles the JSP file into a special servlet file. The servlet is executed and the response object generated by it is sent to the client through the web server. Thus, when a JSP file is accessed for the first time, it requires some time to get the response. If the file is already present in the memory, then the engine checks whether the original JSP file is modified or not. If it is modified, then the JSP file is recompiled and executed. Otherwise it is just executed again. Thus JSP files are automatically recompiled, but pure servlet files should be explicitly recompiled.

Fig.

JSP-Engine

Is request is 1 or 2nd

request

First.jsp

True Page Compile False


Is modified

Web-Server First.java Servlet Server Response sends page to client

The JSP page class file extends HttpJspBase which in turn implements the Servlet interface. It contains 3 methods. Life Cycle of JSP jspInit : performs the initialization of a servlet. This method can be overridden. jspService: executed for every request. jspDestroy: gets executed when servlet is removed by the server. This method can be overridden.

JSP Access Model / JSP Architecture These are based on the location at which the bulk of the request process is preformed. 1. Model 1 (Page Centric Design)

Fig.
JSP

Bean Servlet-Container

EnterprizeInformation System

In this type, the incoming request from a web browser is sent directly to the JSP page, which is responsible for processing it & replaying back to the client. There is still separation of using beans. Although, Model 1

architecture is suitable for simple application, it may not be desirable for complex implementation. This architecture usually leads to significant amount of script-lets embedded within a JSP Page. This may cause problems for web developers who dont know much about Java, but required to develop large websites. The other disadvantage of this architecture is that

each JSP page is individually responsible for managing application state & verifying authentication & security.

2.

Model 2 (Servlet-Centic Design)(MVC-Model View Controller)

The Model-2 architecture is a server-side implementation of the popular MVC design pattern. Here the processing is divided between the presentation and front component. Presentation component are JSP pages that generate the HTML/XML response that determines the user interface when viewed by the browser. Front component controller do not handle any presentation issues, but process all the HTTP requests. Here, they are responsible for creating any beans or objects used by the presentation components, as well as deciding, depending on the users act which presentation components to forward the request to. Front components can be implemented as either a servlet or JSP page. The advantage of this architecture is that, there is no processing logic within the presentation component itself, it is simply responsible for retrieving any objects or beans that may have been previously created by the controller and extracting the dynamic content within for insertion within its static templates. This separation of roles and responsibilities of developers and page designers.

Another advantage of this approach is that the front component present a single point of entry into the application thus making the management of application state, security and presentation uniform and easier to maintain. Write any four JSP Basic syntax JSP Syntax Basics 1. Declarations

JSP Declarations lets you define page level variables or methods. These are like variables or methods declared as class-level member. You can declare static or instance variables or methods. It is declared using <%!....%>.

For eg

<%! int i=0;%> or <%! public void test(){..}%>

numsq.html <html> <form method=get action=http://localhost:8080/ty/numsq.jsp> Enter Num : <input type=text name=t1> <input type=submit> </form> </html>

numsq.jsp <html> Sq:<%=getsq(request)%> </html>

<%! public int getsq( HttServeletRequest req) { int i=Integer.parseInt (req.getParameter(t1)); return i*i; } %>

2.

Expression

They are included <%=.%>. The results of evaluating the expression are converted to a string & directly included within the output page. These are used to display simple variables or return values of methods. For example <%= i %> or <%= bean1.getname() %>

3.

Scriplets The code

JSP code fragments or scriplets are included in<%.....%>.

declared within these tags goes into service method. It includes java code which is to be executed by the server. For example:<%for (int i=1; i<=4;i++) { %> <H <%=i>%>Hello</H<%=i%>> <%}%>

o/p

<H1> Hello </H1> <H2> Hello </H2> <H3> Hello </H3> <H4> Hello </H4>

4.Comments <%-- ................. --%> represents server-side comment. Write a short notes on JSP IncludeDirective, taglibDirectives) Explain any four JSP Page Directives 5 Directives Directives (PageDirective,

JSP directives are messengers for the JSP Engine. They dont directly produce any visible O/P but tell the engine what to do with the JSP page. They are included in <%@.... %> tag. They are used to set the content type, import packages, control buffering, session management etc. The general syntax for directives are:Syntax: <%@ directive attribute name = value..%> There are 3 types of directives :1. Page directives- It defines a no. of important attributes that affect the whole page directives is as follows :

1. contentType sets the MIME content-type <%@ page contentType = text/plain %>

2.import specifies a list of classes & packages, the generated servlet should import. By default, java.lang.*, javax.servlet.*; javax.servlet.http.* & javax.servlet.jsp.* are automatically imported. <%@ page import = java.io.*, java.util.* %>.

3.buffer specifies the minimum requirement size of the response in KBs. A special value none indicates that content should be passed directly to the underlying PrintWriter object. Default is 8Kb. <%@page buffer = 12Kb %>

4.autoFlush specifies if the buffer should be flushed when its filled or IO exception should be thrown. Default is true, because if this attributes is false, then a programmer should manually flush the buffer. <%@ page autoFlush = true %>

5.session indicates the page want to have access to users session. Default is true. <%@ page session = true %>

6.ErrorPage specifies a page to display if an exception occurs within the JSP page. <%@ page errorPage = /error.jsp %> 7.isErrorpage indicates the page is intended to be used as the target on the errorpage. <%@ page isErrorPage=true %>

8.language Default is java.

specifies the scripting language used to write the code.

<%@ page language =javascript%>.

2.

Include Directive The include directive lets you separate your content into more

manageable elements/files. For example, you can design separate html files that display common header/footer and include it in a jsp page. It includes the contents of given file in a current jsp page. <%@ include file=copyright.html %> For example,

3.

Taglib Directive

This directive allows the page to use custom user-defined tags with the specified tag library name. The files have tld(tag library descriptor) extension. These files contain the specification of which classes should be executed when a user-defined tag is encountered. For example <%@ taglib uri=/WEB-INF/struts.tld prefix=struts %> Every user-defined tag is prefixes by a string specified by prefix attribute to avoid problems of tag-name clashes. For example, you can have your own tag called html with a prefix to differentiate it from HTMLs html tag. For example <user:html> .. </user:html>

Write any six implicit objects of JSP JSP Implicit objects JSP container makes available implicit objects to be used within scriptlets and expressions, without the programmer first having to first create them. These objects act as wrappers around underlying java classes and interfaces defined in servlet API. They are as follows 1. request : represents HttpServletReqeust object used to access clients info. 2. response : represents HttpServletResponse object used to send data to client. 3. out : represents JspWriter object that writes into the output stream. 4. config : parameters. represents ServletConfig object used to read initialization

5. session : represents HttpSession object used to identify a client and associate info with it. 6. page : represents HttpJspPage object. Alternatively, you can use this operator to refer to current page. This object is used in custom tag handler classes. 7. application : represents object of ServletContext which is used to obtain information about servlets that are running. 8. pageContext : represents object of PageContext which is used to access context data for page execution. 9. exception : represents Throwable object to handle uncaught errors and exceptions.

Explain the different kind of JSP object scope Object Scope JSP pages include java objects. These objects are either implicit or can be created by the user. These objects can be associated with a scope attribute defining the visibility of that object in different parts of JSP pages or through out the application. You can define objects with following scope--1) application :- identifies objects accessible from pages that belong to the same application (Client independent).
application

Application object

2) session:- identifies objects accessible from pages that belonging to the same session as the one in which they were created.(life of user session, multiple requests from same browser window).
application Session Object Session Object Session Object Session Object Session Object

3) request:- objects accessible from pages processing the request where they were created(before response is sent, accessible also in any included or forwarded pages)
Request object [bring the information from server

Var=getParameter(object Name)

4) page :-objects accessible only within pages where they were created.(current page until it is displayed or control is forwarded to new page)

var varname varname

Its syntax is as follows ----<javaobject </> id = name scope =page/request/session/application

The scope of implicit objects is as follows---1) application 2) request 3) page ---------- ---------- ---------- application request response, pageContext, out, config, page, exception 4) session -------- session

Note :--- All implicit objects are only visible within the system generated jspService method. They are not visible within methods that you define yourself in declarations. 4 JSP implicit objects (request, session, application, pageContext) have the ability to store and retrieve attribute names and values .These are used to share information among jsp and servlets. setAttribute(String key,Object val) String [] getAttributeNames( ) Object getAttribute(String key) removeAttribute(String key)
Key 1001 2001 3001 Object SKumar BKumar AKumar Index 3001 2001 1001

Synchronization Issue By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared variable is synchronized .The other way to use is Thread Safe attribute of page directive <%@ page isThread Safe=false %>

The above declaration causes the JSP pages implementation class to implement single thread model interface, and having multiple instances of servlets to be loaded in the memory. The concurrent client requests are then submitted to individual servlet.

Servlet Instance 1 Req, Res ------Servlet Instance 2 Servlet Instance n Req, Res ---------------------

Req, Res ------Servlet Pool

--------

Servlet Container The disadvantage of using the above method is when large number of concurrent requests are received, the total number of servlet-instances loaded at a time are limited. So a client may have to wait for some time to get a free servlet. Thats why a better approach is to use isThreadSafe to be true (by default, it is true) and to explicitly control access to shared objects.

counter.jsp <html> <%! Integer count = new Integer(0); %> <% synchronized(count) { try { int I = count.intValue(); I++; out.println(this servlet has been accessed + I + number of times); count = new Integer(I); } catch(Exception e) {} } %> </html>

Session Management By default, all JSP pages participate in an HttpSession. Session is used for the purpose to identify a session and to associate information with it to be used for multiple requests coming from same browser window. Sessions are good place for storing beans and objects that need to be shared across other JSP pages and servlets, that may be accessed by the user. The session object is identified by a session id and stored into browser as a cookie. If cookies are not supported by the browser, then the session id may be maintained by URL rewriting a(modifying URL explicitly to include name-value pairs, for example http://localhost:8080/ty/servlet/ser1?t1=1) .

You cannot add primitive data types into the session. valid java objects identified by a unique key.

You can only store

UserCounter.jsp <html> <% int j = 0; out.println(session.getId()); if( (Object) session.getValue(session.getId()) == null) { j = 1; session.putValue(session.getId(), new Integer(1)); } else { Integer k = (Integer) session.getValue(session.getId()); j = k.intValue() + 1; session.putValue(session.getId(), new Integer(j)); } %> You accessed this page for <%= j %> times <a href=http://localhost:8080/ty/UserCounter.jsp> Click </a> </html>

Handling Exceptions When you are creating an application using JSP, you need to make sure that your application handles the errors properly. There are 2 types of errors or exceptions that can generally occur 1. Translation Time Errors

Since JSP pages are compiled automatically by Web server, translation errors can occur during the page compilation. This results in an internal server error ( Error Code 500). The specific error messages displayed for a translation time error depends on your jsp run time container. 2. RunTime Exceptions

These errors occur during the execution of a JSP page. Most of the times, it occurs because of invalid client input. Most of the rime, it results in a stack dump on the client side. In JSP, this can be avoided using error pages as shown below

cal.jsp <html> <%@ page errorPage = error.jsp %> <% int j = 4/0; %> </html>

arith.jsp <html> <%@ page errorPage = error.jsp %> <% int ar [] ={1,2,3}; out.println(ar[6]); %> </html>

error.jsp <html> <%@ page isErrorPage = true %> <% if ( exception instance of ArithmeticException ) { out.println(invalid arithmetic operation ); } else if(exception instanceof ArrayIndexOutOfBoundsException ) { out.println(invalid array subscript); }

%> </html>

Forwards Syntax <jsp:forward page=uri />

You can also specified parameters using <jsp:param> tags

Including Beans JSP allows programmers to make use of beans in them. It is a part of jsp action category. Actions allow programmers to specify how to forward

pages, specify java applets, include beans etc. Actions support XML-based syntax. The syntax for including beans is as follows <jsp:useBean id=BeanName class=ClassName scope=scopevalue />

The main attributes are as follows i) id specified name using which the bean can be accessed, ii) class- specified java class name iii) scope specified scope (application /request/session/page)

To access the properties of bean, the syntax is as follows <jsp:getProperty name=ClassName property=PropertyName />

To set the properties of bean, the syntax is as follows <jsp:setProperty value=Newvalue/> name=ClassName property=PropertyName

To illustrate this, consider the following example

It shows creation of bean and how values can be assigned to the properties of bean and then how they can be used. The program contains a data-entry form accepting roll, name and marks whose input is taken from two files.

Step 1 : Create a directory called mypack in classes folder and create a class file in that package and then compile.

student.java package mypack; public class student { private int roll; private String name; private float marks; public student() {

roll = 0; name = "XYZ"; marks = 0; } public int getRoll() { return roll; } public void setRoll(int r) { if(r>0) roll = r; } public String getName() { return name; } public void setName(String r) { name = r; } public float getMarks() { return marks;

} public void setMarks(float f) { if(f>0) marks = f; } }

Step 2

Now you create HTML/JSP files.

st1.html <html> <form method=get action=st1.jsp> enter roll : <input type=text name=t1> <br> enter name : <input type=text name=t2> <br> <input type=submit value=Next></html>

st1.jsp

<html> <jsp:useBean class="mypack.student" id="s" scope="session"/> <jsp:setProperty name="s" property="roll" value = "<%=Integer.parseInt(request.getParameter("t1")) %>" />

<jsp:setProperty name="s" property="name" value = "<%=request.getParameter("t2") %>" /> <jsp:forward page="st2.jsp" /></html>

st2.jsp

<html> <form method=get action="st3.jsp" > Marks : <input type=text name=t3 > <input type=submit value=Last> </form></html>

st3.jsp

<html> <jsp:setProperty name="s" property="marks" value = "<%=Float.parseFloat(request.getParameter("t3")) %>" /> Roll : <jsp:getProperty name="s" property="roll" /> Name : <jsp:getProperty name="s" property="name" /> Marks : <jsp:getProperty name="s" property="marks" /> </html> JAVABEANS

JavaBeans is a technology that enables to write component software in Java programming language. Components are selfcontained, reusable software units that integrate with each other, with applications and with development tools. JavaBean components are

known as Beans. A Bean can be an entire application used alone or embedded within other application or component that can be used within an application.

What are the advantages of Java Beans What are the advantages of Java component Write beans advantage any 4 four

The advantages of designing applications in terms of components (called as distributed applications) are as follows

1. Component Reuse : Once a component is created for a certain application, it can be used by other developers for their applications. And these components dont require rigorous testing because they are already being tested. 2. Less time and resources : We can use the existing components for our applications and we can save time and resources to develop similar type of programs. 3. Less complexity : The application is divided into objects or components hence the complexity of the entire project is reduced. 4. Less storage space: since multiple applications use the same set of components, replication of the code is prevented saving a lot of memory. Components are classified into two types Visual components and Non-visual components. Visual components are software components

with visual representation that requires a physical space on the display surface of a parent application. For example, button. A non-visual components are software components that dont have visual representation. For example, Spell-check. The following list briefly describes key Bean concepts.

About Beans Development Kit (BDK)

The Bean Development Kit is a tool that allows the user to configure and interconnect a set of beans. It acts as a builder tool for all the beans. It also allows you to manipulate various aspects/features of beans (such as properties, events and methods). Actually it is a java application that acts as a container for all beans. When you install BDK, you need to select a proper java.exe file. BDK consists of many directories such as beanbox, jars, etc. To start BDK, we need to execute run.bat file from bdk\beanbox directory. When started, the BeanBox displays four windows- ToolBox, BeanBox, Properties sheet and Method Tracer (BDK1.1 or higher). 1. Toolbox : The ToolBox contains the Beans available for use by the BeanBox. To work on a Bean, you choose it from the ToolBox and drop it on the BeanBox window. 2. Beanbox: The BeanBox window is the area where you visually wire Beans together, defining how Beans appear, and interact with other Beans. The BeanBox window is itself an instance of a BeanBox Bean. 3. Properties : The Properties sheet displays the properties for the Bean currently selected within the BeanBox window. 4. Method Tracer Window : displays information about the method tracing service.

The BeanBox Menus The following tables explain each item in the BeanBox File, Edit, and View menus. File Menu
Menu Item Save Action Saves the Beans currently in the BeanBox, including each Bean's size, position, and internal state. The saved file can be loaded via File|Load. Saves the Beans in the BeanBox to a serialized (.ser) file. This file must be put in a .jar file to be useable by the BeanBox.

SerializeComponent... MakeApplet... Load... LoadJar... Print Clear Exit

Generates an applet from the BeanBox contents.


Loads saved files into the BeanBox. This command will not load .ser files. Loads a JAR file's contents into the ToolBox. Prints an image of the BeanBox contents. Removes the BeanBox contents. Quits the BeanBox without offering to save.

Edit Menu
Menu Item Cut Action Removes the Bean selected in the BeanBox. The cut Bean is serialized, and can then be pasted. Copies the Bean selected in the BeanBox. The copied Bean is serialized, and can then be pasted. Drops the last cut or copied Bean into the BeanBox. Generates an introspection report for the selected Bean.

Copy Paste Report...

Events Bind property...

Lists the selected Bean's event-firing methods, grouped by the Java interface that declares the methods. Lists all the selected Bean's bound property methods, if any.

View Menu Menu Item Action

Disable Design Removes the ToolBox and the Properties sheet from the screen. Mode/ Enable Eliminates all BeanBox design and test behavior (selected Bean, etc.), and Design Mode makes the BeanBox behave like an application. Hide Beans/ Invisible Hides or shows Beans with no GUI.

Show Invisible Beans

Some of the key components of beans are as follows 1. Builder tools discover a Bean's features (that is, its properties,

methods, and events) by a process known as introspection. Beans support introspection in two ways: i. By adhering to specific rules, known as design patterns (rules to obtain the information about a bean), when naming Bean features. The java.beans.Introspector class examines Beans or these design patterns to discover Bean features. The Introspector class relies on the core reflection API. Reflection obtains information about fields, constructors, methods, parameters, arrays etc from a class file. Reflection is a lower level process. Introspection is a higher-level process that makes use of reflection to classify the information into properties, events and methods. ii. By explicity providing property, method, and event information with a related Bean Information class. A Bean information class implements the

interface. A BeanInfo class explicitly lists those Bean features that are to be exposed to application builder tools. iii. Properties are a Bean's appearance and behavior characteristics that can be changed at design time. Builder tools introspect on a Bean to discover its properties, and expose those properties for manipulation. They map to the fields/variables present in the bean class. Beans expose properties so they can be customized at design time. Customization is supported in two ways: By using property editors, or by using more sophisticated Bean customizers. PropertyEditor classes automatically expose properties in text-field, combo-box or a GUI component. But they are used to change only 1 value at a time. At times you may need to set multiple values in a single component. For example, DBSource ( table name, user name, password, dsn etc). These can be developed using Customizers. iv. Beans use events to communicate with other Beans. A Bean that wants to receive events (a listener Bean) registers its interest with the Bean that fires the event (a source Bean). Builder tools can examine a Bean and determine which events that Bean can fire (send) and which it can handle (receive).
BeanInfo

v. Persistence enables Beans to save and restore their state. Once you've changed a Beans properties, you can save the state of the Bean and restore that Bean at a later time, property changes intact. JavaBeans uses Java Object Serialization to support persistence. Serialization is a process to save the state of an object.
5. Bean's methods are no different than Java methods, and can be called from

other Beans or a scripting environment. By default all public methods are exported(displayed to the user for execution).
JAR Files

JAR stands for JAVA Archive and it provides a standard mechanism platformindependent file format that puts multiple files into one. It becomes very easy to copy a single file for distribution to compress and package a set of files for distribution to the users. JAR is a that can transfer through the network. To make

any bean usable in a builder tool, package all class files that are used by the bean code into a JAR file. A JAR file for a bean needs a manifest file that specifies which class files in the archive are beans and should be included in the Toolbox.

For example, here is the manifest file, SimpleBean.mft (any text file) for the SimpleBean.java file

Name: SimpleBean.class Java-Bean: True


If your bean contains multiple class files, you only mention in the manifest those class files that are beans and that you want to have displayed in the toolbox. Typically a JAR file will contain the class files and auxiliary resources (such as jpg/gif files, other class files etc) associated with applets and applications. The JAR file format provides many benefits:

Security: You can digitally sign the contents of a JAR file. Users who recognize your signature can then optionally grant your software security privileges it wouldn't otherwise have. Decreased download time: If your applet is bundled in a JAR file, the applet's class files and associated resources can be downloaded to a browser in a single HTTP transaction without the need for opening a new connection for each file. Compression: The JAR format allows you to compress your files for efficient storage. Packaging for extensions: The extensions framework provides a means by which you can add functionality to the Java core platform, and the JAR file format defines the packaging for extensions. By using the JAR file format, you can turn your software into extensions as well. Package Sealing: Packages stored in JAR files can be optionally sealed so that the package can enforce version consistency. Sealing a package within a JAR file means that all classes defined in that package must be found in the same JAR file.

Package Versioning: A JAR file can hold data about the files it contains, such as vendor and version information. Portability: The mechanism for handling JAR files is a standard part of the Java platform's core API.

The different options used with jar are as follows c : to create an archieve f : indicates that the first elements in the files is the name of the archieve to be created m : the second element in files is the name of the manifest file t : tabulate the contents of the archieve v : provide verbose output x : extract the contents of jar file 0 : dont use compression u : update existing archieve. Writing a SimpleBean In this section you will learn more about Beans and the BeanBox by Creating a simple Bean Compiling and saving the Bean into a Java Archive (JAR) file Loading the Bean into the ToolBox Dropping a Bean instance into the BeanBox Inspecting the Bean's properties, methods, and events Generating an introspection report

Your Bean will be named SimpleBean. Here are the steps to create it and view it in the BeanBox: 1. Write the SimpleBean code. Put it in a file named SimpleBean.java, in the directory of your choice. Here's the code: import java.awt.*; import java.io.Serializable;

public class SimpleBean extends Serializable { public SimpleBean() { setSize(60,40); setBackground(Color.red); } }

Canvas implements

SimpleBean extends the java.awt.Canvas component. SimpleBean also implements the java.io.Serializable interface, a requirement for all Beans so that they can be saved and restored. SimpleBean sets the background color and component size. 2. Compile the Bean: javac SimpleBean.java This produces the class file SimpleBean.class
3. Create a manifest file. Use your favorite text editor to create a file, we'll call it SimpleBean.mft, that contains the following text:
Name: SimpleBean.class Java-Bean: True Dont forget to press <Enter> key at the end of last line. The manifest file contains which of the classes should be used as the bean.

4. Create the JAR file. The JAR file will contain the manifest and the SimpleBean class file:
jar cfm SimpleBean.jar SimpleBean.mft SimpleBean.class here c-> creates a jar file f -> specifies the name of the jar file(1st file name) m -> specifies manifest file(2nd file name) All the class files are specified in the end.

5. Load the JAR file into the ToolBox. Select the File|LoadJar... menu item. This will bring up a file browser. Navigate to the SimpleBean.jar location and select it. SimpleBean will appear at the bottom of the ToolBox. (Note that when the BeanBox is started, all Beans in JAR files in the beans/jars directory are automatically loaded into the ToolBox).

6. Drop a SimpleBean instance into the BeanBox. Click on the word SimpleBean in the ToolBox. The cursor will change to a crosshair. Move the cursor to a spot within the BeanBox and click. SimpleBean will appear as a painted rectangle with a hatched border. This border means that SimpleBean is selected. The SimpleBean properties will appear in the Properties sheet.

You can resize SimpleBean, because it inherits from Canvas, by dragging a corner. You will see the cursor change to a right angle when over a corner. You can also reposition SimpleBean within the BeanBox by dragging on any non-corner portion of the hatched border. You will see the cursor change to crossed arrows when in position to move the Bean.

Explain design patterns in Java What is design patterns in Java? Explain with the help of example

Design Patterns Design Patterns are rules to determine information about a bean from its reflected method names and signatures. The three major bean design patterns are as follows 1. Property Design Pattern 2. Event Design Pattern 3. Method Design Pattern

What is accessor-mutator
Property Design Pattern

Property Design Patterns are used to identify the publicly accessible properties of a bean. They are closely related to accessor-mutator methods. Accessor-Mutator methods are the means by which JavaBeans automatic introspection facilities determine which properties a bean exposes. Whenever the javabeans introspection mechanism encounters a public getter(Accessor) or setter methods (Mutator methods), it exposes the property to the outside world. The different types of property design patterns are as follows 1. Simple Properties They consist of single-values properties which include all built-in java data types as well as classes and interfaces, such as int, long, char, Color, Font etc. The design property for this type is as follows
Syntax:
public int getNumber1() public <return datatype> get<propname> ( ) { { return varname; return num1; } } public void set<propname> ( <datatype> varname) { public void setNumber(int value) Datamember=varname; { num1=value; }

for example, public int getNum( ) / public void setNum(int n) exposes an integer property called num in the property sheet window(outside world)
Be careful with the capitalization pattern you use for your method names. The bean analyzer performs a process called decapitalization to derive the property name. (That is, the first character after get or set is converted to lower case.)

2. Boolean Properties They are similar to simple property. But Boolean properties are always displayed in combo-box from which a user has to select true/false value. The design pattern for Boolean properties is as follows public boolean is<propname> ( ) { } public void set<propname> (boolean value) { } public boolean get<propname> ( ) { }
boolean paid; public boolean isPaid() { return paid; } public void setPaid(boolean value) { paid=value; }

public boolean getPaid() The difference is that Boolean property makes use of a word is instead of get. If both the methods are present(get as well as is) then is method is preferred. { return paid; }

3. Indexed Properties They are used for setting the values for the arrays. Here we have two get methods and set method, with the entire array or on elements of the array. The design pattern for the indexed properties is as follows //elements of an array public <return type> get<propname> (int I) {
public String getStudname(int index) public String [ ] studname={"Item1","Item2","Item3","Item4"};

} public void set<propname> ( int I, datatype x) { } //entire array public datatype [ ] get<propname> ( ) { } public void set <propname> ( datatype [ ] x) { }

{ return this.studname[index]; } public void setStudname(int index, String studname) { this.studname[index]=studname; } public String [ ] getStudname() { return this.studname; }

Event Design Pattern

JavaBeans provides event-oriented design patterns to give introspecting tools the ability to discover what events a Bean can fire. For a Bean to be the source of an event, it must implement methods that add and remove listener objects for that type of event. The design patterns for these methods are:

public void add<EventListener> (<EventListener> l ) public void remove<EventListener>(<EventListener> l)


Here Event is the type of the event and l is the event listener. add method allows listener to register for the event. By default, multiple listeners can be registered on the same bean. This is known as multicast-event model. But if you want that your bean should send a notification to only one bean at a time, then you need to declare the add method as follows public void add<EventListener>(<EventListener> TooManyListenersException l ) throws

remove method allows a listener to unregister for notifications about a specific type of event. These events appear in the Events menu of a particular bean along with the different types of methods present in the specific listener.

Method Design Pattern Method design patterns are related to public methods that are not accessor methods. Generally these methods are user-defined that server a specific purpose. The names of these methods appear in Target Dialog box when you want to execute a specific task on occurrence of any event. Java Bean Prgs 1. 2. Juggler SimpleBean
import java.awt.*; public class simplebean extends Canvas { public simplebean() { setSize(200,200); } public void paint(Graphics g) { g.drawString("Hello",50,50); } }

3.

SimpleBean with user-defined message


import java.awt.*;

public class simplebean extends Canvas { private String msg;

public simplebean() { setSize(200,200); msg = "Hello"; } public void setMessage(String m) { msg = m; repaint(); } public String getMessage() { return msg; } public void paint(Graphics g) { g.drawString(msg,50,50); } }

4.

Shape Bean without/with Serialiazable

import java.awt.*; //import java.io.*;

public class shapes extends Canvas //implements Serializable { private String stype; private boolean filled; public shapes() { setSize(150,150); stype = "Rect"; filled = false; } public void setShape(String s) { stype = s; repaint(); } public String getShape() { return stype; } public void setFilled(boolean b) { filled = b; repaint(); } public boolean isFilled()

{ return filled; } public void paint(Graphics g) { if(stype.equals("Rect") && filled ) { g.fillRect(100,100,200,200); } else if(stype.equals("Rect") && !filled ) { g.drawRect(100,100,200,200); } else if(stype.equals("Circle") && filled ) { g.fillOval(100,100,200,200); } else if(stype.equals("Circle") && !filled ) { g.fillOval(100,100,200,200); } } }

With Serializable, you can save the state of the object using Save and Load options

5.

Shape Bean with mouse click using Builder tools events

public class shapes extends Canvas implements MouseListener {. Color c; public shapes() { . c = Color.red; addMouseListener(this); } public void paint(Graphics g) { g.setColor(c); } public void mouseClicked(MouseEvent me) { changecolor(); } public void mousePressed(MouseEvent me){} public void mouseReleased(MouseEvent me){} public void mouseEntered(MouseEvent me){} public void mouseExited(MouseEvent me){} public void changecolor() {

int r = (int) ( 255 * Math.random()); int g = (int) ( 255 * Math.random()); int b = (int) ( 255 * Math.random()); c = new Color(r,g,b); repaint(); }

6.

User defined text field accepting either only numbers or only text tf.java import java.awt.*; import java.awt.event.*; public class tf extends TextField { private boolean istext; public tf() { super(10); istext = true; addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent ke) { char c = ke.getKeyChar(); if(c>='0' && c<='9' && istext) ke.consume(); else if( !(c>='0' && c<='9') && !istext) ke.consume(); } } ); } public void setIsText(boolean b) { istext = b; }

public boolean getIsText() { return istext; } } For creating jar file : jar cfm tf.jar tf.mft tf.class tf$1.class Write a short notes on Bound Properties Explain Bound Properties with the help of Example Bound Properties

Sometimes when a Bean property changes, another object may want to be notified of the change, and react to the change. Whenever a bound property changes, notification of the change is sent to interested listeners. A Bean containing a bound property must maintain a list of property change listeners, and alert those listeners when the bound property changes.

SrcProperty1 SrcProperty2 SrcProperty3 Source Bean

Source Property changes

Binding

Reflection taking place at TgtProperty

TgtProperty1 TgtProperty2 TgtProperty3

Target Bean

The convenience class PropertyChangeSupport implements methods that add and remove PropertyChangeListener objects from a list, and fires PropertyChangeEvent objects at those listeners when the bound property changes. Your Beans can inherit from this class, or use it as an inner class. An object that wants to listen for property changes must be able to add and remove itself from the listener list on the Bean containing the bound property, and respond to the event notification method that signals a property change. By implementing the PropertyChangeListener interface the listener can be added to the list maintained by the bound property Bean, and because it implements the PropertyChangeListener.propertyChange method, the listener can respond to property change notifications. The PropertyChangeEvent class encapsulates property change information, and is sent from the property change event source to each object in the property change listener list via the propertyChange method. Following example shows how to implement bound property. The program consists of a source bean that contains a bound property which sends a notification to target bean when the property changes. To implement a bound property, take the following steps: 1. Import the java.beans package. This gives you access to the PropertyChangeSupport class. 2. Instantiate a PropertyChangeSupport object: Syntax: PropertyChangeSupport objname=new private PropertyChangeSupport pcs = PropertyChangeSupport (this);

PropertyChan

New

This object maintains the property change listener list and fires property change events. You can also make your class a PropertyChangeSupport subclass. 3. Implement methods to maintain the property change listener list. Since PropertyChangeSupport implements these methods, you merely wrap calls to the property-change support object's methods: public addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener (l); } public removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener (l); } void

void

When the BeanBox (or Beans-aware builder tool) recognizes the design patterns for bound properties within your Bean, you will see a propertyChange item when you select the Edit Events menu. 4. Modify a property's setter method to fire a property change event when the property is changed. Source beans setName method looks like this:

public void setName(String newname) { String oldname = name; name = newname;

pcs.firePropertyChange("name", oldname, name); } Note that setName stores the old name value, because both the old and new name must be passed to firePropertyChange. Syntax: public void firePropertyChange(String propertyName, Object oldValue, Object newValue) The firePropertyChange method bundles its parameters into a PropertyChangeEvent object, and calls propertyChange (PropertyChangeEvent pce) on each registered listener. The old and new values are treated as Object values. If your property values are primitive types such as int, you must use the object wrapper version such as java.lang.Integer. Also, property change events are fired after the property has changed. Now that you have given your source bean the ability to broadcast events when a bound property has changed, the next step is to create a listener. Note that if a source bean and target bean contains property of the same type and if you want to just copy the value of property from source bean to target bean, then you can make use of Edit Bind property option. When you want to execute some arbitrary code, then you have to make use of propertyChange event.
5.

Implementing Bound Property Listeners To listen for property change events, your listener (Target) Bean must implement the PropertyChangeListener interface. This interface contains one method:

public void propertyChange(PropertyChangeEvent e) This is the notification method that the source Bean calls on all property change listeners in its property change listener list. So to make your class able to listen and respond to property change events, you must: 6. Implement the PropertyChangeListener interface. public class trgbean implements PropertyChangeListener 7. Implement the propertyChange method in the listener. This method needs to contain the code that handles what you need to do when the listener receives property change event. Very often, for example, this is a call to a setter method in the listener class: a property change in the source Bean propagates a change to a property in a listener Bean. To register interest in receiving notification about a Bean property change, the listener Bean calls the listener registration method on the source Bean. For example: public void propertyChange(PropertyChangeEvent e) { System.out.println (e.getPropertyName()); String olds = (String) e.getOldValue(); String news = (String) e.getNewValue(); int I = Integer.parseInt(news); }

Case (I): Using builder menu Bind property when the properties are of same type uname.java [SOURCE BEAN] import java.beans.*; //STEP 1 import java.util.*; import java.io.*; public class uname implements Serializable { private String name; PropertyChangeSupport pcs; //STEP 2 public uname() { name="World"; pcs = new PropertyChangeSupport(this); } public String getName() {

return name; } public void setName(String s) { String oldname = name; name = s; pcs.firePropertyChange("name",oldname,name); //STEP 4 } public void addPropertyChangeListener(PropertyChangeListener l) 3 { pcs.addPropertyChangeListener(l) ; System.out.println("Property Listener added"); } STEP

public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l);

System.out.println("Property Listener removed"); } }

Case (II): Using builder menu propertyChange event when the properties are of different type

uname.java [SOURCE BEAN] import java.beans.*; //STEP 1 import java.util.*; import java.io.*; public class uname implements Serializable { private String name; private PropertyChangeSupport pcs; //STEP 2 public uname() { name="World";

pcs = new PropertyChangeSupport(this); } public String getName() { return name; } public void setName(String s) { String oldname = name; name = s; pcs.firePropertyChange("name",oldname,name); //STEP 4 } public void addPropertyChangeListener(PropertyChangeListener l) 3 { pcs.addPropertyChangeListener(l) ; System.out.println("Property Listener added"); } STEP

public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); System.out.println("Property Listener removed"); } }

unametrg.java

[TARGET BEAN]

import java.beans.*; import java.io.*;

public class unametrg implements PropertyChangeListener, Serializable //STEP 6 { private int i; public unametrg() { i = 0; } public void setI (int j)

{ i = j; } public int getI() { return i; } public void propertyChange(PropertyChangeEvent e) //step 7 { String pname = e.getPropertyName(); if(pname.equals("name")) { String newname = (String) e.getNewValue(); i = newname.length(); } } }

Constrained Properties

Sometimes when a Bean property changes, another object may want to be notified of the change, and react to the change. But the object may react to only select values and may not react to some value. Thus the listener bean accepts only some changes and rejects (vetoes) some values. Such properties are called as constrained properties. Every constrained property is a type of bound property. A Bean property is constrained when any change to that property can be vetoed. Usually an outside object exercises the right to veto, but the Bean itself can also veto a property change. A Bean containing a constrained property must maintain a list of vetoable change listeners, and alert those listeners when the constrained property changes. The convenience class VetoableChangeSupport implements methods that add and remove VetoableChangeListener objects from a list, and fires VetoableChangeEvent objects at those listeners when the constrained property changes. Your Beans can inherit from this class, or use it as an inner class. An object that wants to listen for property changes must be able to add and remove itself from the listener list on the Bean containing the bound property, and respond to the event notification method that signals a property change.

Using some condition


SrcProperty1 SrcProperty2 SrcProperty3 Source Bean

Source Property changes

Binding

Reflection taking place at TgtProperty

TgtProperty1 TgtProperty2 TgtProperty3

Target Bean

By implementing the VetoableChangeListener interface the listener can be added to the list maintained by the bound property Bean, and because it implements the VetoableListener, vetoableChange method, the listener can respond to vetoable change notifications. vetoablaeChange method throws PropertyVetoException because of which the target bean gets the right to accept or reject the change. The PropertyChangeEvent class encapsulates property change information, and is sent from the property change event source to each object in the property change listener list via the vetoableChange method. Following example shows how to implement constrained property. The program consists of a source bean that contains a constrained property name which sends a notification to target bean when the property changes. The target bean contains an integer property whose value equals the length of the string. But the target bean accepts this change only if the user enters a name whose length is less than or equal to 8 characters. Else the target bean rejects the change. To implement a bound property, take the following steps: 1. Import the java.beans package. This gives you access to the VetoableChangeSupport class.

2.

Instantiate a VetoableChangeSupport object: privateVetoableChangeSupport vcs = new

VetoableChangeSup

This object maintains the vetoable change listener list and fires vetoable events. You can also make your class a VetoableChangeSupport subclass.

3. Implement methods to maintain the vetoable change listener list. Since VetoableChangeSupport implements these methods, you merely wrap calls to the propertychange support object's methods: public void addVetoableChangeListener(VetoableChangeListener l) { vcs.addVetoableChangeListener(l); } public void removeVetoableChangeListener(VetoableChangeListener l) { vcs.removeVetoableChangeListener(l); } When the BeanBox (or Beans-aware builder tool) recognizes the design patterns for bound properties within your Bean, you will see a vetoableChange interface item when you select the Edit|Events menu. 1. Modify a property's setter method to fire a vetoable change event when the property is changed.

Source beans setName method looks like this: public void setName(String n) throws PropertyVetoException { String oldname = name; vcs.fireVetoableChange("name", oldname, n); name = n; } Note that setName stores the old name value, because both the old and new name must be passed to fireVetoableChange.

public void fireVetoableChange(String oldValue, Object newValue)

propertyName,

Object

The fireVetoableChange method bundles its parameters into a VetoableChangeEvent object, and calls vetoableChange (VetoableChangeEvent vce) on each registered listener. The old and new values are treated as Object values. If your property values are primitive types such as int, you must use the object wrapper version such as java.lang.Integer. Also, property change events are fired after the property has changed. Now that you have given your source bean the ability to broadcast events when a bound property has changed, the next step is to create a listener.
5.

Implementing Constrained Property Listeners To listen for property change events, your listener (Target) Bean must implement the VetoableChangeListener interface. This interface contains one method: public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException This is the notification method that the source Bean calls on all vetoable change listeners in its property change listener list. So to make your class able to listen and respond to vetoablchange events, you must: public class trgbean implements VetoableChangeListener {

6.

Implement the vetoableChange method in the listener.

This method needs to contain the code that handles what you need to do when the listener receives property change event. Very often, for example, this is a call to a setter method in the listener class: a property change in the source Bean propagates a change to a property in a listener Bean. To register interest in receiving notification about a Bean property change, the listener Bean calls the listener registration method on the source Bean. For example:

public void vetoableChange(PropertyChangeEvent e) throws PropertyChangeEvent { System.out.println(e.getPropertyName()); String olds = (String) e.getOldValue(); String news = (String) e.getNewValue(); int I = Integer.parseInt(news); if ( I > 8) throw new PropertyVetoException(Len>8,e) } About BeanInfo and SimpleBeanInfo A builder tool examines a Bean and exposes its features (properties, events, and methods) in a property sheet. By using the java.beans.Introspector class. The Introspector class uses the JDK core reflection API to discover a Bean's methods, and then applies the JavaBeans design patterns to discover the Beans features. This discovery process is named introspection. Alternatively, you can explicitly expose a Bean's features in a separate, associated class that implements the BeanInfo interface. By associating a BeanInfo class with your Bean, you can:

Expose only those features you want to expose. Rely on BeanInfo to expose some Bean features while relying on low-level reflection to expose others. Associate an icon with the target Bean. Specify a customizer class. Segregate features into normal and expert categories. Provide a more descriptive display name, or additional information about a Bean feature.

BeanInfo defines methods that return descriptors for each property, method, or event that you want exposed. Each of these methods returns an array of descriptors for each feature. BeanInfo classes contain descriptors that precisely describe the target Bean's features. The BDK implements the following descriptor classes: 1. FeatureDescriptor is the base class for the other descriptor classes. It declares the aspects common to all descriptor types. 2. BeanDescriptor describes the target Bean's class type and name, and describes the target Bean's customizer class if it exists. 3. PropertyDescriptor describes the target Bean's properties. 4. IndexedPropertyDescriptor is a subclass of PropertyDescriptor, and describes the target Bean's indexed properties. 5. EventSetDescriptor describes the events the target Bean fires. 6. MethodDescriptor describes the target Bean's methods. 7. ParameterDescriptor describes method parameters. The BeanInfo interface declares these methods that return arrays of the above descriptors. You must create a class that implements BeanInfo interface and append the string BeanInfo at the end of the classname. Alaternatively, you can make use of a convenience class called SimpleBeanInfo that implements BeanInfo methods to return null, or an equivalent no-op value. Using SimpleBeanInfo saves you from implementing all the BeanInfo methods; you only have to override those methods you need.

1.

Student.jar

Student.java import java.awt.*; import java.awt.event.*; import java.util.*;

public class Student extends Panel { private String name=""; private String gender=""; private Color colorobj=Color.pink;

StringListener l;

//listener (event listener)


Property Name

public Student()
Gender Male Pink

{ setSize(100,100); setBackground(Color.pink);
}

Student Compoent

Color

public void addStringListener (StringListener se) throws TooManyListenersException { If (l==null) l = se; else throw new TooManyListenersException(); } public void removeStringListener(StringListener se) { l = null; }

public void setName(String newvalue) { name = newvalue; StringEvent se = new StringEvent(this,name); if(l!=null) l.stringChanged(se); repaint();

public String getName() { return name; }

public void setGender(String genvalue) { gender = genvalue; repaint(); } public String getGender() { return gender; }

public void setColor(Color newcolor) { colorobj = newcolor;

setBackground(colorobj); }

public Color getColor() { return color; }

public void paint(Graphics g)


{ Name: Somvalue Gender: SomeGender

g.drawString(name,75,50); g.drawString(gender,25,50); }
}

StudentBeanInfo.java import java.awt.event.*; import java.lang.reflect.*; import java.beans.*;

public class StudentBeanInfo extends SimpleBeanInfo

{ public PropertyDescriptor [] getPropertyDescriptors() { try { PropertyDescriptor pd1, pd2, pd3; Class classobj = Student.class; pd1 = new PropertyDescriptor("name",classobj); pd2 = new PropertyDescriptor("gender",classobj); pd2.setPropertyEditorClass(genderEditor.class);

pd3 = new PropertyDescriptor("color",classobj); pd3.setPropertyEditorClass(colorEditor.class);

PropertyDescriptor pds[] = { pd1,pd2, pd3 };

return pds; }

catch(IntrospectionException e) { System.out.println(e); return null; }


}

public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor esd1, esd2; String mevents[] = {"mouseClicked"}; esd1 = new EventSetDescriptor(Student.class, "mouse", MouseListener.class, mevents, "addMouseListener", "removeMouseListener");

String sevents[] = {"textChanged"}; esd2 = new EventSetDescriptor(Student.class, "string", StringListener.class, sevents, "addStringListener", "removeStringListener");

EventSetDescriptor esd[] = { esd1,esd2};

return esd; } catch(IntrospectionException e) { System.out.println(e); return null; } } }

genderEditor.java import java.beans.*; public class genderEditor extends PropertyEditorSupport { String options [] = {"Male", "Female"}; public String [] getTags() { return options;

} } colorEditor.java import java.beans.*; import java.awt.*;

public class colorEditor extends PropertyEditorSupport { String options [] = {"red", "green" ,"blue"}; public String [] getTags() { return options; } public String getAsText() { Color colorobj = (Color) getValue(); if(colorobj == Color.red) return "red"; else if(colorobj == Color.green) return "green"; else if(colorobj == Color.blue)

return "blue"; else return null; } public void setAsText(String s) { if(s.equals("red")) setValue(Color.red); if(s.equals("green")) setValue(Color.green); if(s.equals("blue") ) setValue(Color.blue); } }

StringEvent.java import java.util.*; public class StringEvent extends EventObject { private String s;

public StringEvent(Object o, String s) { super(o); this.s = s; } public String getNewString() { return s; } }

StringListener.java import java.util.*;

public interface StringListener extends EventListener { public void textChanged(StringEvent se); }

jar cfm Student.jar Student.mft Student.class StudentBeanInfo.class genderEditor.class colorEditor.class StringEvent.class StringListener.class

2. nametrg.jar

public class nametrg implements StringListener { private String msg; public nametrg() { msg = ""; } public void setMsg(String s) { //msg = s; } public String getMsg() { return msg; } public void stringChanged(StringEvent se) { String s = (String)se.getNewString();

msg = s; } }

The classes and methods used in the above program are as follows 1. PropertyDescriptor

Constructs a PropertyDescriptor for a property that follows the standard Java convention by having get and set accessor methods. public PropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException where the property. beanClass - The Class object for the target bean propertyName - The programmatic name of

(i) public void setPropertyEditorClass(Class propertyEditorClass)

sets the property editor class for the given property. This editor class controls the display of the property in the property sheet window. 2. EventSetDescriptor

An EventSetDescriptor describes a group of events that a given Java bean fires. The given group of events are all delivered as method calls on a single event listener interface, and an event listener object can be registered via a call on a registration method supplied by the event source. EventSetDescriptor(Class sourceClass,String eventSetName, Class listenerType,String[] listenerMethodNames, String addListenerMethodName,String removeListenerMethodName) This constructor creates an EventSetDescriptor using string names.

3.

PropertyEditorSupport

This is a support class to help build property editors. Its is a subclass of PropertyEditor interface and it also adds and removes property change listeners. The property can be displayed in the form of text field, combo box or a GUI component. String [] getTags( )

If the property value must be one of a set of known tagged values, then this method should return an array of the tag values. It

adds a combobox to display the list of values from which user can select any one property.

String getAsText( )

Gets the property value as a string suitable for presentation to a human to edit.

void setAsText(String v) Sets the property value by parsing a given String. The value of the property is obtained as a text.

Object getValue( )

Gets the value of the property.

Void setValue(Object V)

Set (or change) the object that is to be edited.

If you want to build a GUI-based property editor, then you need to do the following

For the first step, you override the getAsText method in the PropertyEditor interface to return null and the isPaintable method to return true.

(i) public String getAsText() { return null; }

(ii) public boolean isPaintable() { return true; }

(iii) Then, you implement the paintValue method. It receives a Graphics context and the coordinates of the rectangle inside which you can paint. Note that this rectangle is typically small, so you can't have a very elaborate representation.

public void paintValue(Graphics g, Rectangle box) { . }

(iv) Of course, this graphical representation is not editable. The user must click on it to pop up a custom editor. You indicate that you will have a custom editor by overriding the supportsCustomEditor in the PropertyEditor interface to return true. public boolean supportsCustomEditor() { return true; }

(v) Now, you write the code that builds up the component that will hold the custom editor. You will need to build a separate custom editor class for every property. public Component getCustomEditor() { return new InverseEditorPanel(this); }

PropertyEditor and Customizer

Bean's appearance and behavior can be customized at design time within Beans-compliant builder tools. Typically there are two ways to customize a Bean: By using a property editor. Each Bean property has its own property editor. A builder tool usually displays a Bean's property editors

in a property sheet. A property editor is associated with, and edits a particular property type. By using customizers. Customizers give you complete GUI control over Bean customization. Customizers are used where property editors are not practical or applicable. Unlike a property editor, which is associated with a property, a customizer is associated with a Bean. A property editor, no matter how sophisticated, is responsible for allowing the user to set one property at a time. Especially if certain properties of a bean relate to each other, it may be more user friendly to give users a way to edit multiple properties at the same time. To enable this feature, you supply a customizer instead of (or in addition to) multiple property editors.

Any customizer class you write must implement the Customizer interface. There are only three methods in this interface: (i) The setObject method, which takes a parameter that specifies the bean being customized; The addPropertyChangeListener and removePropertyChangeListener methods, which manage the collection of listeners that are notified when a property is changed in the customizer.

By definition, a customizer class is visual. It must, therefore, extend Component or a subclass of Component, such as JPanel.

Using the BeanBox to Generate Applets You can use the BeanBox's File|MakeApplet... menu item to generate an applet from the BeanBox contents. Making an applet from the BeanBox creates: A JAR file containing class files and serialized data A test HTML file that uses the JAR file (and any other JAR files needed) A subdirectory with Java sources and makefile A readme file with complete information about the generated applet and all files involved Take the following steps to generate an applet from the BeanBox: Use the Juggler example that you made in the events section. If you saved that example to a file, load it into the BeanBox using the File|Load menu item. If you didn't save it, follow the steps in the events section to build the example. The generated applet will have the same size as the BeanBox frame, so you might want to adjust the BeanBox size to the size of the applet you want. Choose File|Make Applet to bring up the MakeApplet dialog:

Use the default JAR file and applet name for this example. Press the OK button.

The generated files were placed in the beanbox/tmp/myApplet directory. You can inspect your handiwork by bringing up appletviewer in the following way:

appletviewer BDKInstallation>/beanbox/tmp/myApplet.html

Você também pode gostar