Sunteți pe pagina 1din 93

CHAPTER-1

INTRODUCTION OF JAVA
The java programming language is general purpose concurrent class based object oriented language. Itdesign to be simple enough that many programmers can achieve full flex in the language. The java programming language is related to c &c++ but it organize rather different and few ideas from other language include. It is intended to be production language not a research language. The java programming language is strongly typed. This specification clarify distinguishable between the compiler time error that can be and must be detected at compile time and those occur at run time .the java programming language it normally compile to the byte code the java programming language is a relatively high level language instruction set and binary format defined in the java virtual machine specification.

1.1 History:
Java was developed in 1991 and first release come in 1992 , is relatively new programming language it was developed by James Gosling and his team . it was developed at sun Microsystems at U.S. . In 1995 , Netscape incorporated released its latest version of the Netscape browser which was capable of running java program. The original name of the language is OAK,until it was discovered that a programming

language of ready existed that was named OAK . As the history goes after many hours of trying to come up with the new name the

development team went out for cuffed and name Java was born . first it was found for electric and electronic devices and around in 1995 developers had found that java can be used in internet programming. Java was developed by five programmers at Sun Microsystems 1. James Gosling 2. PartickNaughton 3. Chris Wart Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 1

4. Ed Frank

1.2 Java features:


Java is a simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language. One way to characterize a system is with a set of buzzwords. We use a standard set of them in describing Java. Heres an explanation of what we mean by those buzzwords and the problems we were trying to solve. Simple:

We wanted to build a system that could be programmed easily without a lot of esoteric training and which leveraged today's standard practice. Object-Oriented:

This is, unfortunately, one of the most overused buzzwords in the industry. But objectoriented design is very powerful because it facilitates the clean definition of interfaces and makes it possible to provide reusable "software ICs." Network-Savvy:

Java has an extensive library of routines for coping easily with TCP/IP protocols like HTTP and FTP. This makes creating network connections much easier than in C or C++. Java applications can open and access objects across the net via URLs with the same ease that programmers are used to when accessing a local file system. Robust:

Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error prone. Secure:

Java is intended for use in networked/distributed environments. Toward that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 2

Architecture Neutral:

Java was designed to support applications on networks. In general, networks are composed of a variety of systems with a variety of CPU and operating system architectures. Portable:

Being architecture neutral is a big chunk of being portable, but there's more to it than that. Unlike C and C++, there are no "implementation dependent" aspects of the specification. The sizes of the primitive data types are specified, as is the behavior of arithmetic on them. Interpreted:

Java byte codes are translated on the fly to native machine instructions (interpreted) and not stored anywhere. And since linking is a more incremental and lightweight process, the development process can be much more rapid and exploratory. High Performance:

While the performance of interpreted byte codes is usually more than adequate, there are situations where higher performance is required. The byte codes can be translated on the fly (at runtime) into machine code for the particular CPU the application is running on. Multithreaded:

There are many things going on at the same time in the world around us. Multithreading is a way of building applications with multiple threads. Unfortunately, writing programs that deal with many things happening at once can be much more difficult than writing in the conventional single-threaded C and C++ style. Dynamic:

In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment. For example, if A distributes an upgrade to its libraries, then all of the software from B will break. It is possible to avoid this problem in C++, but it is extraordinarily difficult and it effectively means not using any of the language's OO features directly.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 3

CHAPTER-2

JAVA EDITIONS
Java Edition can be categorized into three parts 1. Java 2 Standard Edition (J2SE) 2. Java 2 Enterprise Edition (J2EE) 3. Java 2 Micro Edition (J2ME)

2.1 Java 2 Standard Edition(J2SE) :


J2SE is the Java 2 Standard Edition. J2SE features: Portability JDBC API for database access CORBA technology Java security J2SE consists of two components: Core Java and Desktop Java. Core Java provides back-end functionality, while Desktop Java provides GUI (Graphical User Interface) functionality.

2.2 Java 2 Enterprise Edition (J2EE):


J2EE is Suns preferred Java platform for multi-tier enterprise applications. J2EE enhances J2SE with:

Enterprise JavaBeans components Java Servlets API Java Server Pages XML

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 4

2.3 Java 2 Micro Edition (J2ME):


J2ME is Java 2 Micro Edition. J2ME is designed to run on PDAs, mobile telephones, set-top boxes, and in intelligent cars.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 5

CHAPTER-3

GUI APPLICATION DEVELOPMENT


3.1 GUI Application :
To develop GUI application Java provides two packages 1. Java.awt package 2. Java.swing package

3.1.1java.awt Package:
Contains all of the classes for creating user interfaces and for painting graphics and images. A user interface object such as a button or a scrollbar is called, in AWT terminology, a component. The Component class is the root of all AWT components. See Component for a detailed description of properties that all AWT components share. Some components fire events when a user interacts with the components. The AWT event class and its subclasses are used to represent the events that AWT components can fire. See AWT event for a description of the AWT event model. A container is a component that can contain components and other containers. A con tainer can also have a layout manager that controls the visual placement of components in the container. The AWT package contains several layout manager classes and an interface for building your own layout manager. See Container and Layout Manager for more information

3.1.2 java.Swing Package:


The Swing toolkit includes a rich set of components for building GUIs and adding interactivity to Java applications. Swing includes all the components you would expect from a modern toolkit: table controls, list controls, tree controls, buttons, and labels. Swing is far from a simple component toolkit, however. It includes rich undo support, a highly customizable text package, integrated internationalization and accessibility support. To truly leverage the cross-platform capabilities of the Java platform, Swing supports numerous look and feels, including the ability to create your own look and feel. The ability to create a custom look and feel is made easier with Synth, a look and feel specifically designed to be customized. Swing wouldn't be a component toolkit without Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 6

the basic user interface primitives such as drag and drop, event handling, customizable painting, and window management. Swing is part of the Java Foundation Classes (JFC). The JFC also include other features important to a GUI program, such as the ability to add rich graphics functionality and the ability to create a program that can work in different languages and by users with different input devices. The following list shows some of the features that Swing and the Java Foundation Classes provide.

3.2 Swing GUI Components:


The Swing toolkit includes a rich array of components: from basic components, such as buttons and check boxes, to rich and complex components, such as tables and text. Even deceptively simple components, such as text fields, offer sophisticated functionality, such as formatted text input or password field behavior. There are file browsers and dialogs to suit most needs, and if not, customization is possible. If none of Swing's provided components are exactly what you need, you can leverage the basic Swing component functionality to create your own.

3.3 Java 2D API:


To make your application stand out; convey information visually; or add figures, images, or animation to your GUI, you'll want to use the Java 2D API. Because Swing is built on the 2D package, it's trivial to make use of 2D within Swing components. Adding images, drop shadows, compositing it's easy with Java 2D.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 7

3.4 Difference between awt and swing packages: AWT PACKAGE 1. It use windows logics for GUI application development. 2. Speed fast 3. It does not have rich library SWING PACKAGE 1. It use own logics for application development. 2.Speed slower 3.it have advance library GUI

3.5 Applet

Figure-3.1: Applet Package

This package contains the Applet class --the class that you must subclass if you're writing an applet. Included in this Package is the Audio Clip interface which provides a very high level abstraction of audio. Writing Applets explains the ins and outs of developing your own applets.

3.6 The Abstract Window Toolkit Packages:


Three packages comprise the Abstract Window Toolkit: Java.awt, java.awt.image, and java.awt.peer.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 8

3.6.1 AWT Package: The java.awt package provides graphical user interface (GUI) elements that are used to get input from and display information to the user. These elements include windows, buttons, scrollbars, and text items. 3.6.2 AWT Image Package: The java.awt.image package contains classes and interfaces for managing image data, such as setting the color model, cropping, color filtering, setting pixel values, and grabbing snapshots of the screen. 3.6.3 AWT Peer Package: The java.awt.peer package contains classes and interfaces that connect platformindependent AWT components to their platform-dependent implementation (such as Motif widgets or Microsoft Windows controls). Creating a User Interface covers all three of the AWT packages.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 9

CHAPTER-4

INTRODUCTION TO JDBC
4.1 WHAT IS JDBC AND WHY JDBC?
JDBC(Java Database Connectivity) is a front-tool for connecting to a server and is similar to ODBC in the respect. However, JDBC can connect only Java clients and uses ODBC for the connectivity. JDBC is essentially a low-level Application, Programming Interface. It is called a low-level API since any data manipulation, storage and retrieval has to be done by the program itself. Some tools that provide a higher level abstraction are expected shortly.

4.2 Jdbc Driver Types:


There are four types of JDBC drivers each having its own functionality. Please note that, they do not substitute one another, each having their own suitability aspects. They are classified based on how they access data from the database. 1. Native JDBC DRIVER: A JDBC driver, which is partly written in Java and most of each, implemented using native methods to access the database. This is useful in case of Java application that can run onlyon some specific platforms. Writing these typedrivers is easier compare to writing other drivers. 2. ALL JAVA JDBC NET DRIVERS: A JDBC net drivers which uses a common network protocol to connect to an intermediate server, which is turn employees native calls to connect to the data base. This approach is used for applets where the request must go through the intermediate server. 3. JDBC-ODBC BRIDGE DRIVER: A bridge driver provided with JDBC can convert. The Jdbc calls in to equaling ODBC calls using the native methods. Since ODBC provides for connection to any type of database that is ODBC compliant, to connect a number of databases simultaneously, it is very simple matter. This approach is a recommended once since using ODBC drivers, which are industry standard as of now, would make an application truly portable across the databases. Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 10

4. NATIVE PROTOCOL ALL JAVA DRIVERS: This type of Jdbc driver is written completely in Java and can access the database by making use of native protocols of the database. This method of data access is suitable in case of Intranets were carry everything can run as an application instead of an applet.

4.3 Jdbc Architecture:


JDBC architecture is shown below. Components of JDBC are1.JDBC Driver

Manager2.JDBC Driver3.JDB-ODBC Bridge4. Applications. Uses Native uses special Uses native Calls to net protocols net protocols

Figure 4.1: JDBC Architecture

4.4 Jdbc Driver Manager: Function


of the driver manager is to find out available drivers in the system and connects the application to the appropriate database. Whenever a connection is requested. However, to

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 11

help the driver manager identify different types of drivers, eachdriver should be registered with the driver Manager.

4.5 Jdbc Driver:


Function of the JDBC Driver is to accept the SQL calls from the application and convert them into native calls to thedatabase. However, in this process it may take help some other drivers or even servers, which depends on the type of Jdbc Driver we are using. Also, it is possible that the total functionality of the database server could be built into the driver itself.

4.6 Jdbc-Odbc Bridge:


Sunsoft provides a special JDBC Drivercalled JDBC-ODBC bridge driver, which can beused to connect to any existing database, that is ODBC complaint.

4.7 Application:
Application is a Java Program that needs the information to be modified in some database or wants to retrieve the information.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 12

CHAPTER-5

INTRODUCTION TO HTML
5.1 What Is World Wide Web?
The World Wide Web is a network ofinformation resources. The webrealize onthree mechanisms to make the resources readilyavailable to the widest possible audience: 1.A Uniform name isscheme for locatingresources on the web (E.g.: - URLs) 2. Protocols,for access to named resources over the web (E.g.:-

http).3. Hypertext, for easy navigation amongresources (E.g.: - HTML)The ties between the three mechanisms areapparent throughout this specification.Introduction to

URLsEvery resource available on the web-TMLdocument, image, video clips, program, etc.Has anaddressthatmay be an encoded by aUniform Resource Locator, or "URL"URLs typically consist of three pieces 1. The naming scheme of the mechanism used to access the resource. 2. The name of the machine hosting there source. 3. Thename of the resource itself, givenasapath.Consider the URL that designates the

current html specification:http://www.w3.org//TR/Pr-html4/cover.htmlThis URL may be read as follows: Theyre a document available via an httpprotocol, residing on the machine www.w3.orgAccessible Via the path" TR/Pr-html4/cover.html".Other schemes youmay seein HTML documents include "mail to" for E-mailand FTP for FTP. Here is

anotherexample if aURL. This one refers to a User's mailbox:This is text....For all comments, please send E -mail to<A href="mailto:Joe@ omeplace.com>JoeCool</a>. FRAGMENT IDENTIFIERS Some URLs refer to a location within aresource. This kind of URL ends with "#"followed by an anchor identifier (called the"fragment identifier").

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 13

RELATIVE URLS A relative URL doesn't contain any namingscheme information. Its path generally refersto a resource on the same on the same machineas the current document. Relative

URLs maycontain relative path components (".." meansone level up in the hierarchy defined by thepath), and may contain a baseURL. As an fragment example of

identifiers.Relative URLs are resolved to full URLsusing

relativeURL resolution, assume wehave the baseURLhttp://www.ame.com/support/intro.html . Therelative URL in the followingmarkup for a hypertext link:<A href="supplies.html"> Supplies </a> In HTML, URLs play a role in these situations: Linking to another document or resource. Linking to an external style sheet forinclusion in a page. Images objects and applets for inclusion in apage. Image maps. Form submission Frames Citing an external reference. Referring to metadata conventions describinga document.

5.2 What Is Html?


To publish information for globaldistribution, one needs a universallyunderstood language, a kind of publishingmother tongue that all computers maypotentially understand. The publishing language used by the World Web is HTML

(fromHyperTextMarkupLanguage).HTML gives authors the means to: Publish online documents with headings, text,tables, lists, photos,

etc.Retrieve online information via hypertextlinks, at the click of a button.Design forms for conducting transaction

withremote services, foruse in searching forinformation,makingreservations,orderingproducts

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 14

, etc.Include spreadsheets, video clips, soundclip, and other applications theirdocuments. A BRIEF HISTORY OF HTML

directly in

HTML was originally developed by TimBerners-Lee while at CERN, and popularized bythe Mosaic browser developed at NCSA. Duringthe course of the 1990s it has blossomed withthe explosive growth of the Web. During thistime, HTML has been extended in a number ofways. The Web depends on Web page others andvendors sharing the same conventions for HTML.This has motivated joint work on specificationfor HTML.HTML 2.0 (November 1995) was developed under

the aegis ofthe Internet EngineeringTaskForce (IETF) tocodifycommon practice inlate 1994. HTML+(1993) and [HTML 3.0] HTML 4.0 HTML 4.0 extends HTML with mechanism forstyle sheets, scripting, frames, embeddingobje cts, improved support for right to leftand mixed direction text, richer tables, andenhancementsto forms, offering improvedaccessibility for people with disabilities. INTERNALIZATION This version of HTML has been designed with thehelp of experts in the field of internationallibation, so that document world. may This be has written been ineverylanguage andweb transported accomplished byin co-

easilyaroundthe

prorating [RFC2070], which deals with theinternationalization of HTML. One importantstep has been the adoption of the ISO? IEC:10646 Standard (ISO10646) as the documentcharacter set for HTML. This is the world'smost inclusive standard dealing with issues ofthe representation of international characters,test direction, punctuation, and other worldlanguage issues. HTML now offers greater support fordiverse human languages within a document.This allow s for more effective indexing ofdocuments for search engines, higherqualitytypography, better text-to-text-speechconversion, correct hyphenation, etc. AccessibilityAs the Web community grows and its membersdiversify in their abilities and skills, it iscrucial that the underlying technologies be appropriate to their specific needs.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 15

HTML hasbeen designed to make Web pages more accessible to those with physical limitations.HTML 4.0 developments in the area ofaccessibility include: Encouraging the use of style sheets to achieve layout effect. Making it easier to provide alternate descriptions of images for non-visual browsers. Providing labels for form fields. Providing labelled hierarchical groupings for form fields. Providing the ability to associate a longer text description with an HTML element. Tables Authors now have greater control overstructure and layout (e.g., column groups).The of designers to recommend ability

columnwidths allows user agents to display tabledata

incrementally as it arrives rather thanwaiting for the entire table before rendering. Compound Documents HTML now offers a standard mechanism

forembedding generic media objects andapplications in HTML documents. The OBJECTele ment (together with its more specificancestor amechanism for elements IMG and APPLET) provides video,

including

images,

sound,mathematics, specialized applications, andother objects in a document. It also allowsau thors to specify a hierarchy of alternaterenderings for user agents that don't supporta specific rendering.

5.3 Style Sheets:


Style Sheets simplify HTML markup andlargely relieve HTML of the responsibilitiesof prese ntation. They give both authors andusers control over the presentation ofdocuments-font information, alignment, colours, etc.The mechanism for associating a stylesheet with a documentation dependent of the style sheet language .Before the advent ofstyle sheets, authors and hadlimited control overrendering. HTML 3.2 included a number ofattributes and elements offering control over alignment, font size, and text colour.

Authorsalso exploitedtables and images as a meansfor laying out pages. The relatively long timeit takes for users to upgrade their browsersmeans that these features will continue to beused for some time.

5.4 Components Of Www: Webpage:

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 16

The part of the Web the user sees thefront-end" is known as a Web page, made up oflinks, images, navigation tools text, etc.Web documents are files of informationresiding at a Web site. These documents areusually coded in HyperTextMarkupLanguage (HTML).

5.5 Home Page:


Home page is the first page of web-documents. Home page is theentry point for

thatparticularWWWsite. Also, home page isthe page a browser loads. Every browser hasits own home page. However, the defaulthomepage for a browser can be changed.

5.6 Link:
A link can be anything on a page such astext or graphics, is a gateway to another page within the sight, sore to an entirelydifferent site.

5.7 Web Sites:


A group of related pages is a site. They are the pages to go on

the Web. Companies,Government agencies, institutions,individuals, etc maintain the web sites.

5.8 Web Servers:


Web sites are housed on a server, which is acomputer design to "serve" the file up to theuser in a proper format. Itis also refer toas the "Back-

end" and is actually softwarethat runs at a web site and returns webdocuments upon request b y the web browser.Servers run all the time and wait for users to request information The web gets its name, in fact, from theinterdependent network of servers

worldwide.The user's computer is a terminal, or endpoint, in this network.

5.9 Hepertext:
The operation web realizes on hypertextas its means of interacting with users.Hypertext is

basicallythe same regular text-it can be stored read, searched or edited-with an important extension: Hypertextcontains connections with in the text to otherdocuments. This new text would themselveshave links and a connection to others documents. Continually selecting

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 17

Hypertext islike taking a free-associative tool ofinformation. In

this way,

hypertext

links,called hyper links, can create a complexvirtual web of connections.

5.10 Gateway Programs:


Programs that accept and process requestfrom a web server and generate new web pages.These programs add a new level ofinteractivity on the web not possible bysimple HTML documents.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 18

CHAPTER-6

SERVLET
6.1 Introduction:
The Servlet API consists of two packages, javax.servlet and javax.servlet.http. The javax is there because servlets are a standard extension to Java, rather than a mandatory part of the API. This means that while servlets are official Java, Java virtual machine developers arent required to include the classes for them in their Java development and execution environments. As mentioned already, however, the Servlet API is required for J2EE 1.3.

6.1.1 The Advantages of Servlets Over Traditional CGI:


Java servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies. Efficient

With traditional CGI, a new process is started for each HTTP request. If the CGI program itself is relatively short, the overhead of starting the process can dominate the execution time. With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads, but only a single copy of the servlet class would be loaded. This approach reduces server memory requirements and saves time by instantiating fewer objects. Finally, when a CGI program finishes handling a request, the program terminates. This approach makes it difficult to cache computations, keep database connections open, and perform other optimizations that rely on persistent data. Servlets, however, remain in memory even after they complete a response, so it is straightforwardto store arbitrarily complex data between client requests. Convenient

Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 19

such high-level utilities. Besides, you already know the Java programming language. Why learn Perl too? Youre already convinced that Java technology makes for more reliable and reusable code than does Visual Basic, VBScript, or C++. Why go back to those languages for server-side programming? Powerful

Servlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not without using a server-specific API. Communicating with the Web server makes it easier to translate relative URLs into concrete path names, for instance. Multiple servlets can also share data, making it easy to implement database connection pooling and similar resource-sharing optimizations. Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations. Portable

Servlets are written in the Java programming language and follow a standard API. Servlets are supported directly or by a plug-in on virtually everymajor Web server. Consequently, servlets written for, say, iPlanet Enterprise Server can run virtually unchanged on Apache, Microsoft Internet Information Server (IIS), IBM Web- Sphere, or StarNineWebStar. They are part of the Java 2 Platform, Enterprise Edition (J2EE; see http://java.sun.com/j2ee/), so industry support for servlets is becoming even more pervasive. Secure

One of the main sources of vulnerabilities in traditional CGI stems from the fact that the programs are often executed by general-purpose operating system shells. So, the CGI programmer must be careful to filter out characters such as backquotes and semicolons that are treated specially by the shell. Implementing this precaution isharder than one might think, and weaknesses stemming from this problem are constantly being uncovered in widely used CGI libraries. A second source of problems is the fact that some CGI programs are processed by languages that do not automatically check array or string bounds. For example, in C and C++ it is perfectly legal to allocate a 100-element array and then write into the 999th element, which is really some random part of program memory. So, programmers who forget to perform this check open up their system to deliberate oraccidental buffer overflow Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 20

attacks. Servlets suffer from neither of these problems. Even if a servlet executes a system call (e.g., with Runtime.exec or JNI) to invoke a program on the local operating system, it does not use a shell to do so. And, of course, array bounds checking and other memory protection features are a central part of the Java programming language. Inexpensive

There are a number of free or very inexpensive Web servers that are good for development use or deployment of low- or medium-volume Web sites. Thus, with servlets and JSP you can start with a free or inexpensive server and migrate to more expensive servers with highperformance capabilities or advanced administration utilitiesonly after your project meets initial success. 6.2 The Servlet Lifecycle: When the servlet is first created, its init method is invoked, so init is where youput one-time setup code. it is not called again foreach user request. So, it is used for one-time initializations, just as with the initmethod of applets. After this, each user request results in a thread that calls theservice method of the previously created instance. Multiple concurrent requestsnormally result in multiple threads calling service simultaneously, although yourservlet can implement a special interface (SingleThreadModel) that stipulates thatonly a single thread is permitted to run at any one time. The service method thencalls doGet, doPost, or another doXxxmethod, depending on the type of HTTPrequest it received. Finally, when the server decides to unload a servlet, it first callsthe servlets destroy method. When a client makes a request involving a servlet, the server loads and executes the appropriate Java classes. Those classes generate content, and the server sends the content back to the client. In most cases, the client is a web browser, the server is a web server, and the servlet returns standard HTML. From the web browsers perspective, this isnt any different from requesting a page generated by a CGI script, or, indeed, standard HTML. On the server side, however, there is animportant difference: persistence.* Instead of shutting down at the end of each request, the servlet can remain loaded, ready to handle subsequent requests.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 21

Figure-6.1:Servlet Life-cycle The request-processing time for a servlet can vary, but it is typically quite fast when compared to a similar CGI program. The real performance advantage of a servlet, however, is that you incur most of the startup overhead only once. When a servlet loads, its init() method is called. You can use init() to create I/O-intensive resources, such as database connections, for use across multiple invocations. If you have a high-traffic site, the performance benefits can be quite dramatic. Instead of putting up and tearing down a hundred thousand database connections, the servlet just needs to create a connection once.After the init() method runs, the servlet container marks the servlet as available. For each incoming connection directed at a particular servlet, the container calls the service() method on the servlet to process the request. The service() method can have access to all the resources created in the init() method. The servlets destroy() method is called to clean up resources when the server shuts down.Because servlets are persistent, you can actually remove a lot of filesystem and/or database accesses altogether. For example, to implement a page counter, you can simply store a number in a static variable, rather than consulting a file (or database) for every request. Using this technique, you need to read and write to the disk only ccasionally to preserve state. Since a servlet remains active, it can perform other tasks when it is not servicing client requests, such as running a background processing thread (i.e., where clients connect to the servlet to view a result) or even acting as an RMI host, enabling a single servlet to handle connections from multiple types of clients.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 22

For example, if you write an order processing servlet, it can accept transactions from both an HTML form and an applet using RMI. The Servlet API includes numerous methods and classes for making application development easier. Most common CGI tasks require a lot of fiddling on the programmers part; even decoding HTML form parameters can be a chore, to say nothing of dealing with cookies and session tracking. Libraries exist to help with these tasks, but they are, of course, decidedly nonstandard. You can use the Servlet API to handle most routine tasks, thus cutting development time and keeping things consistent for multiple developers on a project.

6.3 Writing Servlets:


The three core elements of the Servlet API are the javax.servlet.Servlet interface, the javax.servlet.GenericServlet class, and the javax.servlet.http .HttpServlet class. Normally, you create a servlet by subclassing one of the two classes, although if you are adding servlet capability to an existing object, you may find it easier to implement the interface. The GenericServlet class is used for servlets that dont implement any particular communication protocol. Heres a basic servlet that demonstrates servlet structure by printing a short message:

importjavax.servlet.*; import java.io.*; public class BasicServlet extends GenericServlet { public void service(ServletRequestreq, ServletResponseresp) throwsServletException, IOException { resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); // We won't use the ServletRequest object in this example out.println("Hello."); }

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 23

BasicServlet extends the GenericServlet class and implements one method: service(). Whenever a server wants to use the servlet, it calls the service() method, passing ServletRequest and ServletResponse objects (well look at these in more detail shortly). The servlet tells the server what type of response to expect, gets a PrintWriter from the response object, and transmits its output. The GenericServlet class can also implement a filtering servlet that takes output from an unspecified source and performs some kind of alteration. For example, a filter servlet might be used to prepend a header, scan servlet output or raw HTML files for <DATE> tags and insert the current date, or remove <BLINK> tags. A more advanced filtering servlet might insert content from a database into HTML templates. Although most servlets today work with web servers, theres no requirement for that in GenericServlet; the class implements just that, a generic servlet. As well see in a moment, the HttpServlet class is a subclass of GenericServlet that is designed to work with the HTTP protocol. It is entirely possible to develop other subclasses of GenericServlet that work with other server types.

For example, a Java-based FTP server might use servlets to return files and directory listings or perform other tasks, although this capability has in general been underutilized. Later versions of the API have increased the coupling between servlets and HTTP.

6.4 Http Servlets:


The HttpServlet class is an extension of GenericServlet that includes methods for handling HTTP-specific data. HttpServlet provides a number of methods, such as doGet(), doPost(), and doPut(), to handle particular types of HTTP requests (GET, POST, and so on). These methods are called by the default implementation of the service() method, which figures out what kind of request is being made and then invokes the appropriate method. Heres a simple HttpServlet:

importjavax.servlet.*;

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 24

importjavax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { public void doGet(HttpServletRequestreq, HttpServletResponseresp) throwsServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<HTML>"); out.println( "<HEAD><TITLE>Have you seen this before?</TITLE></HEAD>"); out.println( "<BODY><H1>Hello, World!</H1><H6>Again.</H6></BODY></HTML>"); }

} HelloWorldServlet demonstrates many essential servlet concepts. First, HelloWorldServlet extends HttpServlet. This is standard practice for an HTTP servlet. HelloWorldServlet defines one method, doGet(), which is called whenever anyone requests a URL that points to this servlet. The doGet() method is actually called by the default service() method of HttpServlet. The service() method is called by the web server when a request is made of HelloWorldServlet; the method determines what kind of HTTP request is being made and dispatches the request to the appropriate doXXX() method (in this case, doGet()). doGet() is passed two objects, HttpServletRequest and HttpServletResponse, that contain information about the request and provide a mechanism for the servlet to produce output, respectively.ThedoGet() method itself does three things. First, it sets the output type to text/html, which indicates that the servlet produces standard HTML as its output. Second, it calls the getWriter() method of theHttpServletResponse parameter to get a java.io.PrintWriter that points to the client. Finally, it uses the stream to send some HTML back to the client. This isnt really a whole lot different from the BasicServlet example, but it gives us all the tools well need later on for more complex web applications.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 25

We do have to explicitly set the content type, as there is no default setting, even for HTTP servlets where one might reasonably expecttext/html.If you define a doGet() method for a servlet, you may also want to override the getLastModified() method of HttpServlet. The server calls getLastModified() to find out if the content delivered by a servlet has changed. The default implementation of this method returns a negative number, which tells the server that the servlet doesnt know when its content was last updated, so the server is forced to call doGet() and return the servlets output.

If you have a servlet that changes its display data infrequently (such as a servlet that verifies uptime on several server machines once every 15 minutes), you should implement getLastModified() to allow browsers to cache responses. getLastModified() should return a long value that represents the time the content was last modified as the number of milliseconds since midnight, January 1, 1970, GMT. This number can be easily obtained by calling the getTime() method java.util.Date. A servlet should also implement getServletInfo(), which returns a string that contains information about the servlet, such as name, author, and version (just like getAppletInfo() in applets). This method is called by the web server and generally used for logging purposes. It is a mini server side program. It is used to create dynamic and protocol Independent web page. It is loaded and executed on web server .The output of servlet is sent to client as response. The output of servlet is static page in MIME format. The Security issue which are associated with in a java applet, not applicable for servlet because client gets the output of servlet that may be temper by virus .If your web server is Secured behind firewall then you can say your servlet is also secured.

6.4.1 Working of servlet: Servlet is a server side program and it is executed only on the request of client. It is executed only on the request of client .It works behind the web Server that handles client request

Client makes a request either using web browser or any other pages. Web browser of client send the request as HTTP request as a web server. Web server located the requested servlet using web container.
Page 26

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

The servlet engine executes the servlet and generates the MIME response for client. The web server deployed servlet into other page.

6.4.2 Deploying Servlet into jsdk 2.1: The sun micro system provides the jsdk (java servlet development kit) to develop, debug and deploy the servlet. It contains the container two jar files. 1-server.jar 2-servlet.jar The servlet.jar contains the java web server that works on port 8080. The servlet.jar file contains the servlet-api that has two packages1-javax.servlet 2-javax.servlet.http It is very old kit, today other serves are used like tomcat, j2ee, server, jobes etc.

set the classpath of .jar file simply create does batch file to set class path , in which write following code and save with .bat extension in folder where your servlet is stored

Run this batch file on command prompt Compile your servlet .Start the java web server using command start server .IT will open be deployed and last line will be end crated :8080. Dont close this command prompt until end of application execution.

When we start the server then it automatically loads all the servlet in web container Write the following URL in web browser to get response of servlet.

http://localhost:8080/servlet/servlet_name

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 27

6.4.3 Deployment Descriptor: When we deploy our servlet using tomcat/J2EE server/Jbossetc then we write an XML code to configure our application on web server. It is an XML code. It provides a declarative mechanism for customization our web application without touching source code.
<?xml version=1.0 encoding=1s0-8859-1> <web_app> <Sevlet> <servlet-class ></servlet-class> <servlet-name></servlet-name> </servlet> <servlet-mapping> <Serverlet-name></serverlet-name> <use-pattern></use-pattern> </servlet-mapping> <welcome-filr-list> <welcome-file></welcome-file> <welcome-file-list> <web-app>

6.4.4 Deploying the servlet using apache tomcat: It is freeware. It provides facility to deploy the servlet and Jsp.Download it form its home site and install it.

Figure-6.2: Deploying Servlet Using Apache Tomcat To deploy the servlet use following step-: Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 28

set the class path of servlet-api.jar. you will find this file in lib folder of tomcat. Create the servlet program Create following folder structure for your web application under the folder webapps. Copy servlet-api.jar file from tomcat lib to lib your application. Set the class path of servlet-api.jar file. Compile the program an put .class file in folder classes. Write following URL in web browser to get the output http://localhost:9090/application-name/Servlet-name.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 29

The servlet.jar contains the java web server that works on port 8080. The servlet.jar file contains the servlet-api that has two packages1-javax.servlet 2-javax.servlet.http It is very old kit, today other serves are used like tomcat, j2ee, server, jobes etc.

set the classpath of .jar file simply create does batch file to set class path , in which write following code and save with .bat extension in folder where your servlet is stored

Run this batch file on command prompt Compile your servlet .Start the java web server using command start server .IT will open be deployed and last line will be end crated :8080. Dont close this command prompt until end of application execution.

When we start the server then it automatically loads all the servlet in web container Write the following URL in web browser to get response of servlet.

http://localhost:8080/servlet/servlet_name

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 30

CHAPTER-7

JAVA SERVER PAGE(JSP)


7.1 Inroduction:
JSP are the web pages which are compiled at the server side and displayed at the Client Side. Jsp are the pre compiled code used as the HTML Tags. The Need for JSP Servlets are not so good at presentation. Servlets have the following deficiencies when it comes to generating the output. It is hard to write and maintain the HTML. Using print statements to generate HTML? Hardly convenient: you have to use parentheses and semicolons, have to insert backslashes in front of embedded double quotes, and have to use string concatenation to put the content together. Besides, it simply does not look like HTML, so it is harder to visualize You cannot use standard HTML tools like dreamweaver. All those great Web-site development tools you have are of little use when you are writing Java code. The HTML is inaccessible to non-Java developers. If the HTML is embedded within Java code, a Web development expert who does not know the Java programming language will have trouble reviewing and changing the HTML. Benefits of JSP JSP pages are translated into servlets. So, fundamentally, any task JSP pages can perform could also be accomplished by servlets. However, this underlying equivalence does not mean that servlets and JSP pages are equally appropriate in all scenarios. The issue is not the power of the technology, it is the convenience, productivity, and maintainability of one or the other. After all, anything you can do on a particular computer platform in the Java programming language you could also do in assembly language. But it still matters which you choose. JSP provides the following benefits over servlets alone:

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 31

It is easier to write and maintain the HTML. Your static code is ordinary HTML: no extra backslashes, no double quotes, and no lurking Java syntax. You can use standard Web-site development tools. For example, we use Macromedia Dreamweaver for most of the JSP pages in the book. Even HTML tools that know nothing about JSP can be used because they simply ignore the JSP tags. You can divide up your development team. The Java programmers can work on the dynamic code. The Web developers can concentrate on the presentation layer. On large projects, this division is very important. Depending on the size of your team and the complexity of your project, you can enforce a weaker or stronger separation between the static HTML and the dynamic content. JSP Versus .NET and Active Server Pages (ASP) .NET is well-designed technology from Microsoft. ASP.NET is the part that directly competes with servlets and JSP. The advantages of JSP are two fold. First, JSP is portable to multiple operating systems and Web servers you arent locked into deploying on Windows and IIS. Although the core .NET platform runs on a few nonWindows platforms, the ASP part does not. You cannot expect to deploy serious ASP.NET applications on multiple servers and operating systems. For some applications, this difference does not matter. For others, it matters greatly. Second, for some applications the choice of the underlying language matters greatly. For example, although .NETs C# language is very well designed and is similar to Java, fewer programmers are familiar with either the core C# syntax or the many auxiliary libraries. In addition, many developers still use the original version of ASP. With this version, JSP has a clear advantage for the dynamic code. With JSP, the dynamic part is written in Java, not VBScript or another ASPspecific language, so JSP is more powerful and better suited to complex applications that require reusable components. You could make the same argument when comparing JSP to the previous version of ColdFusion; with JSP you can use Java for the real code and are not tied to a particular server product. However, the current release of ColdFusion is within the context of a J2EE server, allowing developers to easily mix ColdFusion and servlet/JSP code.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 32

JSP Versus PHP PHP (a recursive acronym for PHP: Hypertext Preprocessor) is a free, open-source, HTML-embedded scripting language that is somewhat similar to both ASP and JSP. One advantage of JSP is that the dynamic part is written in Java, which already has an extensive API for networking, database access, distributed objects, and the like, whereas PHP requires learning an entirely new, less widely used language. A second advantage is that JSP is much more widely supported by tool and server vendors than is PHP. Versus Pure Servlets JSP doesnt provide any capabilities that couldnt, in principle, be accomplished with servlets. In fact, JSP documents are utomatically translated into servlets behind the scenes. But it is more convenient to write (and to modify!) regular HTML than to use a zillion println statements to generate the HTML. Plus, by separating the presentation from the content, you can put different people on different tasks: your Web page design experts can build the HTML by using familiar tools and either leave places for your servlet programmers to insert the dynamic content or invoke the dynamic content indirectly by means of XML tags. Then What is the need of Servlets 1. JSP pages get translated into servlets. You cant understand how JSP works without understanding servlets. 2. JSP consists of static HTML, special-purpose JSP tags, and Java code. What kind of Java code? Servlet code! You cant write that code if you dont understand servlet programming. 3. Some tasks are better accomplished by servlets than by JSP. JSP is good at generating pages that consist of large sections of fairly well structured HTML or other character data. Servlets are better for generating binary data, building pages with highly variable structure, and performing tasks (such as redirection) that involve little or no output. 4. Some tasks are better accomplished by a combination of servlets and JSP than by either servlets or JSP alone. Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 33

Versus JavaScript JavaScript, which is completely distinct from the Java programming language, is normally used to dynamically generate HTML on the client, building parts of the Web page as the browser loads the document. This is a useful capability and does not normally overlap with the capabilities of JSP (which runs only on the server). JSP pages still include SCRIPT tags for JavaScript, just as normal HTML pages do. In fact, JSP can even be used to dynamically generate the JavaScript that will be sent to the client. So, JavaScript is not a competing technology; it is a complementary one.

7.2JavaServer Pages:
It is used to create the dynamic web page. It is loaded and executed on the client to the web server and output of jsp page is sent to the client. It mean that it is server side --programming technique .It provide very powerful way to handle the handle the server request. It is very flexible and powerful language. It provides the support for all the common web server like IIS, Apache, Tomcat, Web-Logic etc. Using JSP we can create large and complex multi their application .It provide the support Xml data .It can be deployed on any platform .It uses the java language as its core ,which increase the programming capabilities .

It is better than Asp, Asp.net because it can be deployed and deployed using any
operating system .It is faster that Asp and Asp.net an also provide very powerful security to the business logic .It uses the oop architecture that increase the power .It provide very high memory management that result very high-speed memory management that result very high-speed response .It support IP4 and Ip6.It support http pipelining. o It is very user friendly because the syntax of Jsp is very similar to java programming .It provide JIT (just in compiler) for fast execution. It provides the facility of embedded java code in HTML using Script .IT is uses the servlet technique, as is background. o Then the container group like servlet engine, jsp engine, EJP grabber takes what you have written in your jsp, transmits it into a servlet class source file and then compiles that into a java script class. After that the servlet runs in exactly the same Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 34

way as you have deployed previously .In other words ,the container loads the servlet class and initializes it, makes a separate thread for each calls the service() method of servlet. 7.2.1 Working of Jsp: JavaServerPagesaremadeoperablebyhavingtheircontents(HTMLtags,JSPtagsandscripts) translatedintoaservletbytheapplicationserver.Thisprocessisresponsiblefortranslatingboththedy namicandstaticelementsdeclaredwithintheJSPfileintoJavaservletcodethatdeliversthetranslated contentsthroughtheWebserveroutputstreamtothebrowser.

1. The Web browser makes a request to the JSP page. 2. The JSP engine parses the contents of the JSP file. 3. The JSP engine creates temporary servlet source code based on the contents of the JSP. The generated servlet is responsible for rendering the static elements of the JSP specified at design time in addition to creating the dynamic elements of the page. 4. The servlet source code is compiled by the Java compiler into a servlet class file. 5. The servlet is instantiated. The init and service methods of the servlet are called, and the servlet logic is executed. 6. The combination of static HTML and graphics combined with the dynamic elements specified in the original JSP page definition are sent to the Web browser through the output stream of the servlets response object.

Figure-7.1: The JSP processing life-cycle on first-time Invocation Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 35

SubsequentinvocationsoftheJSPfilewillsimplyinvoketheservicemethodoftheservletcreatedbyth eaboveprocesstoservethecontenttotheWebbrowser.Theservletproducedasaresultoftheabovepro cessremainsinserviceuntiltheapplicationserverisstopped,theservletismanuallyunloaded,oracha ngeismadetotheunderlyingfile,causingrecompilation.

7.3 Components Of Javaserver Pages:


JavaServer Pages are composed of standard HTML tags and JSP tags. The available JSP tags defined in the JSP 1.0 specification are categorized as follows: Directives Declarations Scriptlets Comments Expressions

This section describes each of these categories in more detail. Requirement: To create the using JSP we need to install following. 1- web server-: Install the web server that provides support for jsp. 2- API for Jsp-: Install the basic API and JSP. Suppose we are using Apache tomcat. It provides both web server and JSP API. It is freeware open source software. Difference between JSP and Servlet-: The JSP uses servlet technology as its core but it is difference between from servlet 1- The JSP is used embedded to java code in HTML .But in servlet the HTML code should be part of code of classes, 2- If we make any changes in the code of servlet then to get effects of changes we should following steps

Save and recompile the servlet manually.-Stop the web server.-Start the web browser.-Re-open the servlet.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 36

3- JSP is more compact, flexible and extensible than servlet. Time-delay: There are two delays associated with JSP page 1- Translation Time : At the first request of JSP page the container automatically compiles JSP page into equivalent servlet. The time taken by translator is known as translation delay. It depends

configuration of server machine number of threads

2- Response Delay: The time difference b/n request and response is known as response delay. It depends on

Communication medium b/w server requester. Traffic load. Data transmission speed.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 37

CHAPTER-8

SESSION TRACKING AND COOKIES


8.1 Introduction:
Cookies spent a year or two as a little-known feature of Netscape Navigator before becoming the focus of a raging debate on electronic privacy. Ethical and moral considerations aside, cookies allow a web server to store small amounts of data on client systems. Cookies are generally used to store basic user identification or configuration information. Because a cookies value can uniquely identify a client, cookies are often used for session tracking (although, as well see shortly, the Servlet API provides higher-level support for this). To create a cookie, the server (or, more precisely, a web application running on the server) includes a Cookie header with a specific value in an HTTP response. The browser then transmits a similar header with that value back to the server with subsequent requests, which are subject to certain rules. The web application can use the cookie value to keep track of a particular user, handle session tracking, etc. Because cookies use a single Cookie header, the syntax for a cookie allows for multiple name/value pairs in the overall cookie value.

8.2 Cookies In Servlet:


The Servlet API includes a class, javax.servlet.http.Cookie, that abstracts cookie syntax and makes it easy to work with cookies. In addition, HttpServletResponse provides an addCookie() method and HttpServletRequest provides a getCookies() method to aid in writing cookies to and reading cookies from the HTTP headers, respectively. To find a particular cookie, a servlet needs to read the entire collection of values and look through it:
Cookie[] cookies; cookies = req.getCookies(); String userid = null; for (inti = 0; i<cookies.length; i++) if (cookies[i].getName().equals("userid")) userid = cookies[i].getValue();

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 38

A cookie can be read at any time, but can be created only before any content is sent to the client. This is because cookies are sent using HTTP headers. These headers can be sent to the client before the regular content. Once any data has been written to the client, the server can flush the output and send the headers at any time, so you cant create any new cookies safely. You must create new cookies before sending any output. Heres an example of creating a cookie:
String userid = createUserID(); // Create a unique ID Cookie c = new Cookie("userid", userid); resp.addCookie(c); // Add the cookie to the HTTP headers

Note that a web browser is only required to accept 20 cookies per site and 300 total per user, and the browser can limit each cookies size to 4096 bytes. Cookies can be customized to return information only in specific circumstances. In particular, a cookie can specify a particular domain, a particular path, an age after which the cookie should be destroyed, and whether the cookie requires a secure (HTTPS) connection. A cookie is normally returned only to the host that specified it. For example, if a cookie is set by server1.company.com, it isnt returned to server2.company.com. You can get around this limitation by setting the domain to .company.com with the setDomain() method of Cookie. By the same token, a cookie is generally returned for pages only in the same directory as the servlet that created the cookie, or its returned under that directory. We can get around this limitation using setPath(). Heres a cookie that is returned to all pages on all toplevel servers at company.com:
String userid = createUserID(); // Create a unique ID Cookie c = new Cookie("userid", userid); c.setDomain(".company.com"); // *.company.com, but not *.web.company.com c.setPath("/"); // All pages resp.addCookie(c); // Add the cookie to the HTTP headers

8.3Session Tracking :
Very few web applications are confined to a single page, so having a mechanism for tracking users through a site can often simplify application development. The Web, however, is an inherently stateless environment. A client makes a request, the server fulfills it, and both promptly forget about each other. In the past, applications that needed to deal with a user Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 39

through multiple pages (for instance, a shopping cart) had to resort to complicated dodges to hold onto state information, such as hidden fields in forms, setting and reading cookies, or rewriting URLs to contain state information.The Servlet API provides classes and methods specifically designed to handle session tracking. A servlet can use the session-tracking API to delegate most of the user-tracking functions to the server. The first time a user connects to a sessionenabled servlet, the servlet simply creates a javax.servlet.http.HttpSession object. The servlet can then bind data to this object, so subsequent requests can read the data. After a certain amount of inactive time, the session object is destroyed.

A servlet uses the getSession() method of HttpServletRequest to retrieve the current session object. This method takes a single boolean argument. If you pass true, and there is no current session object, the method creates and returns a new HttpSession object. If you pass false, the method returns null if there is no current session object.
For example: HttpSessionthisUser = req.getSession(true);

When a new HttpSession is created, the server assigns a unique session ID that must somehow be associated with the client. Since clients differ in what they support, the server has a few options that vary slightly depending on the server implementation. In general, the servers first choice is to try to set a cookie on the client (which means that getSession() must be called before you write any other data back to the client). If cookie support is lacking, the API allows servlets to rewrite internal links to include the session ID, using the encodeURL() method of HttpServletResponse. This is optional, but recommended, particularly if your servlets share a system with other, unknown servlets that may rely on uninterrupted session tracking. However, this on-the-fly URL encoding can become a performance bottleneck because the server needs to perform additional parsing on each incoming request to determine the correct session key from the URL. (The performance hit is so significant that the Java Web Server disables URL encoding by default.)To use URL encoding run all your internal links through encodeURL(). If you have a line of code like this:
out.println("<A HREF=\"/servlet/CheckoutServlet\">Check Out</A>"); you should replace it with: out.print("<A HREF=\"");

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 40

out.print(resp.encodeURL("/servlet/CheckoutServlet"); out.println("\">Check Out</A>");

JWS, in this case, adds an identifier beginning with $ to the end of the URL. Otherservers have their own methods. Thus, with JWS, the final output looks like this:
<A HREF="/servlet/CheckoutServlet$FASEDAW23798ASD978">Check Out</A>"

In addition to encoding your internal links, you need to use encodeRedirectURL() to handle redirects properly. This method works in the same manner as encodeURL().* You can access the unique session ID via the getID() method of HttpSession. This is enough for most applications, since a servlet can use some other storage mechanism (i.e., a flat file, memory, or a database) to store the unique information (e.g., hit count or shopping cart contents) associated with each session. However, the API makes it even easier to hold onto session-specific information by allowing servlets to bind objects to a session using the putValue() method of HttpSession. Once an object is bound to a session, you can use the getValue() method.Objects bound using putValue() are available to all servlets running on the server. The system works by assigning a user-defined name to each object (the String argument); this name is used to identify objects at retrieval time. In order to avoid conflicts, the general practice is to name bound objects with names of the form

applicationname.objectname. For example:


session.putValue("myservlet.hitcount", new Integer(34));

Now that object can be retrieved with:


Integer hits = (Integer)session.getValue("myservlet.hitcount")

8.4 HttpSessionBindingListener :
Sometimes it is useful to know when an object is getting bound or unbound from a session object. For instance, in an application that binds a JDBC java.sql. Connection object to a session (something that, by the way, is ill-advised in all but very low traffic sites), it is important that the Connection be explicitly closed when the session is destroyed.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 41

The javax.servlet.http.HttpSessionBindingListener interface handles this task. It includes two methods, valueBound() and valueUnbound(), that are called whenever the object that implements the interface is bound or unbound from a session, respectively. Each of these methods receives an HttpSessionBindingEvent object that provides the name of the object being bound or unbound and the session involved in the action. Here is an object that implements the HttpSessionBindingListener interface in order to make sure that a database connection is closed properly:
classConnectionHolder implements HttpSessionBindingListener { java.sql.ConnectiondbCon; publicConnectionHolder(java.sql.Connection con) { dbCon = con; } public void valueBound(HttpSessionBindingEvent event) { // Do nothing } public void valueUnbound(HttpSessionBindingEvent event) { dbCon.close();

} }

8.5 Session Contexts:


Version 2.0 of the Servlet API included the getContext() method of HttpSession, coupled with an interface named HttpSessionContext. Together, these allowed servlets to access other sessions running in the same context. Unfortunately, this functionality also allowed a servlet to accidentally expose all the session IDs in use on the server, meaning that an outsider with knowledge could spoof a session. To eliminate this minor security risk, the session-context functionality was deprecated in Version 2.1 of the Servlet API. Instead, web applications can
Page 42

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

use the getAttribute() and setAttribute() methods of ServletContext to share information across sessions. Databases and Non-HTML Content Most web applications need to communicate with a database, either to generate dynamic content or collect and store data from users, or both. With servlets, this communication is easily handled using the JDBC API . However, servlet developers should keep a few things in mind for optimal performance. First, JDBC Connection objects can be created in the servlets init() method. This allows the servlet to avoid reconnecting to the database (a la CGI) with each request, saving up to a second or more on every single page request.If you anticipate high volume, you may want to create several connections and rotate between them.An excellent freewareconnectionpoolingsystem isavailableathttp://www.javaexchange.com. Or, if youre using JDBC 2.0, the javax.sql package provides a connection-pooling mechanism. Finally, if you plan on using JDBCs transaction support, you need to create individual connections for each request or obtain exclusive use of a pooled connection. So far, all our servlets have produced standard HTML content. Of course, this is all most servlets ever do, but its not all that they can do. Say, for instance, that your company stores a large database of PDF documents within an Oracle database, where they can be easily accessed. Now say you want to distribute these documents on the Web. Luckily, servlets can dish out any form of content that can be defined with a MIME header.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 43

coding
9.1 Source code:

Chapter-9

</tr> <tr> <td>Password : </td> <td><input type="password" name="tpass" value="" size="40" id="frm" /></td> </tr> <tr> <td><input type="reset" value="clear" /></td> <td><input type="submit" value="Sign In" /></td> </tr> </tbody> </table>

</form>

New User? <a href="UserRegistrationForm.jsp" >Sign Up</a> </td> <td> <div style="padding:10px;background:orange; text-shadow:1px 1px 1px gray;font-size:16px;width:50%" >Expert Login</div> <form method="POST" action="ExpertLoginProcess.jsp" onsubmit="return checkForm1()" > <table border="1">

<tbody> <tr>

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 44

<td>Expert ID : </td> <td><input /></td> </tr> <tr> <td>Password : </td> <td><input type="password" name="tpass" value="" size="40" /></td> </tr> <tr> <td><input type="reset" value="clear" /></td> <td><input type="submit" value="Sign In" /></td> </tr> </tbody> </table> type="text" name="tname" value="" size="40"

</form> New Expert? <a href="ExpertRegistrationForm.jsp" >Sign Up</a> </td> </tr> </tbody> </table>

</div>

</body>

9.2 Userprofile.jsp: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 45

<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <link rel="stylesheet" type="text/css" href="master.css" > <style > .abc { background-color: blueviolet; border-radius: 30px 30px 30px 30px; margin:5px; width:200px; height:100px; box-shadow: 5px 5px 5px black; text-align: center; font-size:24px; color:white; font-family:"verdana"; } </style> </head> <body> <%@include file="CheckSession.jsp" %>

<%@include file="header.jsp" %> <div style="border-radius:10px 10px;background:orange; box-shadow:10px 10px 10px gray;width:80%;height:400px;position:relative;left:10%;top:10%"> <h1>Hello User #<%= session.getAttribute("userid")%></h1> <a href="Logout.jsp" >Sign Out</a> <table border="0" width="60%" cellspacing="20px" > <tbody align="center" > <tr>

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 46

<td><button class="abc" onclick="location.replace('UpdateUserProfileForm.jsp')" >Update Profile</button></td> <td><button class="abc" onclick="location.replace('TestCategory.jsp')" >Available Tests</button></td> </tr> <tr> <td><button class="abc" onclick="location.replace('SingleUploadForm.jsp')" >Upload Photo</button></td> <td><button class="abc" onclick="location.replace('ShowResult.jsp')" >View Results</button></td> </tr> </tbody> </table>

<% String path=(String)session.getAttribute("userid")+".jpg";

%> <img style="border-style:none;border-radius:10px;position:absolute;width:28%;boxshadow:5px 5px 10px black;height:240px;left:70%;top:5%" src="<%=path %>" width="200" height="300" /> </div>

</body> </html>

9.3 Test form.jsp: <%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*" %> <!DOCTYPE html> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 47

<html> <head> <style> td{ padding:20px} .main { border-radius:10px; text-shadow: 10 10 10; border: solid blue 1px; position:relative; width:80%; left:10%; height:80%; top:10%; background:orange; box-shadow: 10px 10px 10px rgb(192,192,192); color:white;

} .count {

border: solid white 1px; position:absolute; width:80; left:95%; height:80; top:0%; background:blue; color:white; font-size:28px } </style> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 48

<script>

function countdown() { obj=document.getElementById("count"); obj.innerHTML=parseInt(obj.innerHTML)-1; setTimeout('countdown()',1000); } </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body onload="countdown()" > <%@include file="CheckSession.jsp" %> <jsp:include page="header.jsp" /> <% int duration=Integer.parseInt(request.getParameter("duration")); %> <jsp:useBean id="mc" scope="page" class="pack.MyConnection" /> <br> <div class="main" > <div class="count" id="count" ><%= duration*60 %></div> <form method="post" action="ResultProcess.jsp" > <input type="hidden" name="tid" value=<%= request.getParameter("tid") %> > <table width="90%" border="1" align="center" > <% ResultSet rs = mc.getResult("select * from QuestionMaster qm,Rel_Test_Question as rtq where qm.qid=rtq.qid and rtq.tid=" request.getParameter("tid")); int i=1; while (rs.next()) { Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 49

as +

out.println("<tr><td>"); out.println("<br>"+i+". "+rs.getString("question")); out.println("<br><br>A. <input type=radio value=1 name=answer"+i+" > "+rs.getString("option1")); out.println("<br>B. "+rs.getString("option2")); out.println("<br>C. "+rs.getString("option3")); out.println("<br>D. "+rs.getString("option4")); <input <input <input type=radio type=radio type=radio value=2 value=3 value=4 name=answer"+i+" name=answer"+i+" name=answer"+i+" > > >

out.println("</td></tr>"); i++; } %> <tr> <td><input type="submit" value="End Test" ></td> </tr> </table> <input type="hidden" name="marks" value="<%= request.getParameter("marks") %>" > <input type="hidden" name="totq" value="<%= request.getParameter("totq") %>" > </form> </div> </body> </html>

9.4 Showresult.jsp: <%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*" %> <!DOCTYPE html> <html> <head>

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 50

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <script type="text/javascript" src="jquery.js" ></script> <script type="text/javascript" > $(document).ready(abc); function abc() { $(":radio:first").attr("checked","checked"); } </script> </head> <body onload="abc()" > <%@include file="CheckSession.jsp" %> <jsp:include page="header.jsp" /> <jsp:useBean id="mc" scope="page" class="pack.MyConnection" /><br> <div style="border-radius:10px 10px;background:orange; box-shadow:10px 10px 10px gray;width:80%;position:relative;left:10%;top:10%"> <form method="post" action="Certificate.jsp" > <table width=90% border="1" align="center" > <tr><td colspan="5" align="center"><input type="submit" value="View Certificate" ></td></tr> <% ResultSet rs=mc.getResult("select uid="+session.getAttribute("userid")); while(rs.next()) { out.println("<tr><td><input type=radio name=rid value="+rs.getString(1) +" ></td><td> result # "+rs.getString(1)+"</td><td>test # "+rs.getString(3) +"</td><td>Result : "+rs.getString(4) +"% </td><td>Test Date : "+rs.getDate(5) +"</td></tr>"); } Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 51

from

Rel_User_Test

where

%> </table> </form> </div> </body> </html>

9.5 Certificate .jsp: <%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <style> .main { border: double 5px black; background-color:rgb(250,2500,250); width:60%;

left:10%; top:10%; text-align:center; font-size:14px; font-family: times new roman; position: absolute; color: brown; Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 52

line-height: 50px; padding:100px; box-shadow: 5px 5px 20px black; } </style> </head> <body> <%@include file="CheckSession.jsp" %> <center><input type="button" value="print" onclick="window.print()" ></center> <jsp:useBean id="mc" scope="page" class="pack.MyConnection" /> <% ResultSet rs = mc.getResult("select * from UserMaster as um,Rel_User_Test as rut where rut.uid=um.userid and um.userid=" + session.getAttribute("userid") + " and rut.resultid=" + request.getParameter("rid")); rs.next(); java.util.Calendar cal=java.util.Calendar.getInstance(); cal.setTimeInMillis(rs.getDate("tdate").getTime()); %> <div class="main" ><br> <div style="text-align:left">Serial #<%= rs.getString("resultid")%></div> <br><span style="font-size:28px"> <b>Course Certificate</b> </span><br> <span style="font-size:18px" >This is to certify that Mr./Miss/Mrs. <b><%= "&nbsp&nbsp"+rs.getString("uname").toUpperCase()+"&nbsp&nbsp" %></b> is successfully completed his/her "&nbsp&nbsp"+rs.getString("tid")+"&nbsp&nbsp" %></b> Test # <b><%=

on Date <b> &nbsp&nbsp<%= cal.get(java.util.Calendar.DATE)+"/"+(cal.get(java.util.Calendar.MONTH)+1)+"/"+cal.get(ja va.util.Calendar.YEAR)+"&nbsp&nbsp" %></b>. He/She Achieved <%= "&nbsp&nbsp"+rs.getInt("marks")+"&nbsp&nbsp"%> % Marks in Exam. </span><% java.util.Calendar d=java.util.Calendar.getInstance(); %> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 53

<div style="text-align:left;font-size:24px"><br><br> _<%= d.get(java.util.Calendar.DATE)+"/"+(d.get(java.util.Calendar.MONTH)+1)+"/"+d.get(java.ut il.Calendar.YEAR) %>_ </div> <div style="text-align:right;font-size:24px">Sign.</div> </div>

</body> </html>

9.6 : Index.jsp: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="master.css" > <title>JSP Page</title> <script type="text/javascript" src="validation.js" ></script> <script type="text/javascript" src="jquery.js" ></script> <script type="text/javascript" > $(document).ready(abc); function abc() {

} function checkForm() { str="" t1=document.getElementsByName("tname")[0]; t2=document.getElementsByName("tpass")[0]; if(isEmpty(t1)) Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 54

str+="\n"+"-User Name Can not be Empty"; if(isEmpty(t2)) str+="\n"+"-Password Can not be Empty"; if(str.length>0) { alert("Validation Error :"+str); return false; } else return true; } function checkForm1() { str="" t1=document.getElementsByName("tname")[1]; t2=document.getElementsByName("tpass")[1]; if(isEmpty(t1)) str+="\n"+"-Expert Name Can not be Empty"; if(isEmpty(t2)) str+="\n"+"-Password Can not be Empty"; if(str.length>0) { alert("Validation Error :"+str); return false; } else return true; } </script> </head> <body> <jsp:include page="header.jsp" /> <div style="border-radius:10px 10px;background:orange; box-shadow:10px 10px 10px gray;width:80%;height:400px;position:relative;left:10%;top:10%"> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 55

<p id="mytd"></p> <br> <table width="100%" >

<tbody> <tr><td></td></tr> <tr align="center"> <td>

<div style="padding:10px;background:orange; text-shadow:1px 1px 1px gray;font-size:16px;width:50%" >Student Login</div> <form checkForm()" > <table border="1"> method="POST" action="LoginProcess.jsp" onsubmit="return

<tbody>

<tr> <td>User ID : </td> <td><input /></td> type="text" name="tname" value="" size="40"

9.7About user.html:
<!--

To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 56

<head> <title>About us</title> </head> <BODY bottomMargin=0 aLink=#f0f0f0 leftMargin=90 rightMargin=90 link=#f0f0f0 topMargin=5 bgColor=#98afc7 vLink=#f0f0f0 > <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%" bgColor=#4e9258> <TR> <TD vAlign=top align=middle> <TABLE bgcolor=#f0f0f0 border=0 cellSpacing=0 cellPadding=0 width=140 align=center> <TR> <TD height=100 width="25%"><IMG border=0 alt="" src="images/logo.jpg" width=250 height=100>&nbsp;</TD> <TD height=100 width="50%"><IMG border=0 alt="" src="images/logo.jpg" width=580 height=100> </TD> <TD height=100 width="25%"><IMG border=0 alt="" src="images/logo.jpg" width=250 height=100>&nbsp;</TD> </TR></TABLE> <TABLE border=10 cellSpacing=10 cellPadding=0 width="100%" bgColor=#54c571> <TR> <TD bgColor=#e56e94 vAlign=top align=middle><FONT color=#000000 size=3 face<=Arial><B><A href="index.jsp">HOME</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 57

face=Arial><B><A href="Students.html">Student</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="institutes.html">Institute</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="about_us.html">About Us </A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="FAQ.html">Help/FAQ</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><A href="contact.html"><B>Contact us</B></A></FONT></TD> </TR></TABLE> <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%"> <TR> <TD bgColor=#617c58><B><FONT color=#ff7000 size=3 face=Tahoma center> <MARQUEE onmouseover=this.stop() onmouseout=this.start()>Take a..<FONT color=#cf000 size=2 face=Tahoma><A href="home.jsp"> Sample Online Test</A></FONT></MARQUEE></FONT></B></TD></TR></TABLE> <br> <TABLE border=0 cellSpacing=0 cellPadding=10 width="100%"> <TR> <TD bgColor=#c0c0c0 vAlign=top width="18%" align=middle>&nbsp; <TABLE border=10 cellSpacing=10 cellPadding=10 width="100%" bgColor=#4e8975> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 58

<TR> <TD bgColor=#54c571 width="100%"><FONT size=4 face=Arial><B>Main Menu</B></FONT></TD></TR> <TR> <TD bgColor=#a74ac7 width="100%"><B><FONT size=2 face=Arial><A href="home.jsp">Sample Exam</A></FONT></B></TD></TR> <TR> <TD bgColor=#a74ac7 width="100%"><B><FONT size=2 face=Arial><B><A href="FAQ.html">Help/FAQ </A></B></FONT></B></TD></TR></TABLE> <P> <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%" bgColor=#f87431> <TR> <TD width="100%" align=middle><B><FONT color=#ffffff size=2 face=Arial>Made By:</FONT></B></TD></TR></TABLE> <TABLE border=0 cellSpacing=10 cellPadding=10 width="100%" bgColor=#bce954> <TR> <TD bgColor=#e0ffff width="100%"><FONT size=2 face=Arial>vineetchourasia</FONT></TD></TR></TABLE>

<P> </P> <P></P> <TD bgcolor=#ffffff vAlign=top width="61%" align=left> <P><BR><FONT color=#ff0000 size=5 face="Lucida Calligraphy"><B> <H1><marquee width="100%" bgcolor="yellow" behavior="alternate">OnlineExams</marquee></H1></B></FONT> <br><center><img src="images/logo_2.jpg" width="450" height="200"></center> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 59

<font size=4 face=arial><i> <p> Online Exams is a web application that establishes a network between the institutes and the students. Institutes enter on the site the questions they want in the exam. These questions are displayed as a test to the eligible students. The answers enter by the students are then evaluated and their score is calculated and saved. This score then can be accessed by the institutes to determine the passes students or to evaluate their performance. </p> <p> Online Exams provides the platform but does not directly participate in, nor is it involved in any tests conducted. Questions are posted not by the site, but users of the site. The site requires an institute to register before posting the questions. </p> <p> The system entitled Online Exams is application software, which aims at providing services to the institutes and providing them with an option of selecting the eligible students by themselves. It is developed by using J2EE technology and related database. </p> </i></font> </TABLE> <br> </TABLE> </body> </html>

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 60

9.8contact.html

<!-To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <title>Institutes</title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> </head> <BODY bottomMargin=0 aLink=#f0f0f0 leftMargin=90 rightMargin=90 link=#f0f0f0 topMargin=5 bgColor=#98afc7 vLink=#f0f0f0 > <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%" bgColor=#4e9258> <TR> <TD vAlign=top align=middle> <TABLE bgcolor=#f0f0f0 border=0 cellSpacing=0 cellPadding=0 width=140 align=center> <TR> <TD height=100 width="25%"><IMG border=0 alt="" src="images/logo.gif.JPG" width=250 height=100>&nbsp;</TD> <TD height=100 width="50%"><IMG border=0 alt="" src="images/logo.jpg" width=580 height=100> Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 61

</TD> <TD height=100 width="25%"><IMG border=0 alt="" src="images/logo.gif.JPG" width=250 height=100>&nbsp;</TD> </TR></TABLE> <TABLE border=10 cellSpacing=10 cellPadding=0 width="100%" bgColor=#54c571> <TR> <TD bgColor=#e56e94 vAlign=top align=middle><FONT color=#000000 size=3 face<=Arial><B><A href="index.jsp">HOME</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="Students.html">Student</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="institutes.html">Institute</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="about_us.html">About Us </A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><B><A href="FAQ.html">Help/FAQ</A></B></FONT></TD> <TD bgColor=#e56e94 vAlign=top align=middle><FONT size=3 face=Arial><A href="contact.html"><B>Contact us</B></A></FONT></TD> </TR></TABLE> <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%"> <TR> <TD bgColor=#617c58><B><FONT color=#ff7000 size=3 face=Tahoma Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 62

center> <MARQUEE onmouseover=this.stop() onmouseout=this.start()>Take a..<FONT color=#cf000 size=2 face=Tahoma><A href="home.jsp"> Sample Online Test</A></FONT></MARQUEE></FONT></B></TD></TR></TABLE> <br> <TABLE border=0 cellSpacing=0 cellPadding=10 width="100%"> <TR> <TD bgColor=#c0c0c0 vAlign=top width="18%" align=middle>&nbsp; <TABLE border=10 cellSpacing=10 cellPadding=10 width="100%" bgColor=#4e8975> <TR> <TD bgColor=#54c571 width="100%"><FONT size=4 face=Arial><B>Main Menu</B></FONT></TD></TR> <TR> <TD bgColor=#a74ac7 width="100%"><B><FONT size=2 face=Arial><A href="home.jsp">Sample Exam</A></FONT></B></TD></TR> <TR> <TD bgColor=#a74ac7 width="100%"><B><FONT size=2 face=Arial><B><A href="FAQ.html">Help/FAQ </A></B></FONT></B></TD></TR></TABLE> <P> <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%" bgColor=#f87431> <TR> <TD width="100%" align=middle><B><FONT color=#ffffff size=2 face=Arial>Made By:</FONT></B></TD></TR></TABLE> <TABLE border=0 cellSpacing=10 cellPadding=10 width="100%" Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 63

bgColor=#bce954> <TR> <TD bgColor=#e0ffff width="100%"><FONT size=2 face=Arial> Vineet chourasia </FONT></TD></TR></TABLE> </TD> <P> </P> <P></P> <TD bgcolor=#ffffff vAlign=top width="61%" align=left> <P><BR><FONT color=#ff0000 size=5 face="Lucida Calligraphy"><B> <H1><marquee width="100%" bgcolor="yellow" behavior="alternate">OnlineExams</marquee></H1></B></FONT> <br><img src="images/institutes_1.jpg" width="300" height="250" align="left"> <font size=4 face=arial><i> Online Exams fulfills the requirements of the institutes to conduct the exams online. They do not have to go to any software developer to make a separate site for being able to conduct exams online. They just have to register on the site and enter the exam details and the lists of the students which can appear in the exam. </i></font> <br><br> <font size=4 face=arial> <i> Online Exams is a web application that establishes a network between the institutes and the students. Institutes enter on the site the questions they want in the exam. These questions are displayed as a test to the eligible students. The answers enter by the students are then evaluated and their score is calculated and saved. This score then can be accessed by the institutes to determine the passes students or to evaluate their performance.
Page 64

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

</i></font> </TABLE> <br> </TABLE> </body> </html>

9.9Home page: face=Arial><B><A href="FAQ.html">Help/FAQ </A></B></FONT></B></TD></TR></TABLE> <P> <TABLE border=10 cellSpacing=0 cellPadding=0 width="100%" bgColor=#f87431> <TR> <TD width="100%" align=middle><B><FONT color=#ffffff size=2 face=Arial>Made By:</FONT></B></TD></TR></TABLE> <TABLE border=0 cellSpacing=10 cellPadding=10 width="100%" bgColor=#bce954> <TR> <TD bgColor=#e0ffff width="100%"><FONT size=2 face=Arial> Vineet chourasia </FONT></TD></TR></TABLE> </TD> <P> </P> <P></P> <TD bgcolor=#ffffff vAlign=top width="61%" align=left> <P><BR><FONT color=#ff0000 size=5 face="Lucida Calligraphy"><B> <H1><marquee width="100%" bgcolor="yellow" behavior="alternate">OnlineExams</marquee></H1></B></FONT>

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 65

<br><img src="images/institutes_1.jpg" width="300" height="250" align="left"> <font size=4 face=arial><i> Online Exams fulfills the requirements of the institutes to conduct the exams online. They do not have to go to any software developer to make a separate site for being able to conduct exams online. They just have to register on the site and enter the exam details and the lists of the students which can appear in the exam. </i></font> <br><br> <font size=4 face=arial> <i> Online Exams is a web application that establishes a network between the institutes and the students. Institutes enter on the site the questions they want in the exam. These questions are displayed as a test to the eligible students. The answers enter by the students are then evaluated and their score is calculated and saved. This score then can be accessed by the institutes to determine the passes students or to evaluate their performance. </i></font> </TABLE> <br>

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 66

CHAPTER -10

PROJECT(Web Application)
10.1INTRODUCTION:
OnlineExamsis being launched because a need for a destination that is beneficial for both Institutes and students. With this site, institutes can register and host online exams. Students can give exams and view their results. This site is an attempt to remove the existing flaws in the manual system of conducting exams. Purpose Online Exams Systemfulfills the requirements of the institutes to conduct the exams online. They do not have to go to any software developer to make a separate site for being able to conduct exams online. They just have to register on the site and enter the exam details and the lists of the students which can appear in the exam. Students can give exam without the need of going to any physical destination. They can view the result at the same time. Thus the purpose of the site is to provide a system that saves the efforts and time of both the institutes and the students. What is Online Exams System all about? Online ExamsSystem is a web application that establishes a network between the institutes andthe students. Institutes enter on the site the questions they want in the exam. These questions aredisplayed as a test to the eligible students. The answers enter by the students are then evaluatedand their score is calculated and saved. This score then can be accessed by the institutes todetermine the passes students or to evaluate their performance. Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 67

Online Exams Systemprovides the platform but does not directly participate in, nor is it involved in any tests conducted. Questions are posted not by the site, but users of the site. Thesite requires an institute to register before posting the questions. The site has an administrator who keeps an eye on the overall functioning of the system. The sitegets revenue by charging the institutes each time they want to conduct the exam. The system entitled Online Exams System is application software, which aims at providing services to the institutes and providing them with an option of selecting the eligible students bythemselves. It is developed by using J2EE technology and related database.

10.2. Software Development Methodology


The establishment and use of sound engineering principles in order to obtain economicallydeveloped software that is reliable and works efficiently on real machines is called softwareengineering. Software engineeringis the discipline whose aim is: 1. Production of quality software 2. software that is delivered on time 3. cost within the budget 4. satisfies all requirements. Software process is the way in which we produce the software. Apart from hiring smart,knowledgeable engineers and buying the latest development tools, effective softwaredevelopment process is also needed, so that engineers can systematically use the best technicaland managerial practices to successfully complete their projects. A software life cycle is the series of identifiable stages that a software product undergoes duringits lifetime .A software lifecycle model is a descriptive and diagrammatic representation of thesoftware life cycle .A life cycle model represents all the activities required to make a softwareproduct transit through its lifecycle phases .It also captures the order in which these activities are to be taken.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 68

10.2.1. Life Cycle Models


There are various life cycle models to improve the software processes. WATERFALL MODEL PROTOTYPE MODEL ITERATIVE ENHANCEMENT MODEL EVOLUTIONARY MODEL SPIRAL MODEL

10.2.2. WATERFALL MODEL This model contains 6 phases: oFeasibility study The feasibility study activity involves the analysis of the problem andcollection of the relevant information relating to the product. The main aimof the feasibility study is to determine whether it would be financially andtechnically feasible to develop the product.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 69

oRequirement analysis and specification The goal of this phase is to understand the exact requirements of thecustomer and to document them properly.(SRS) oDesign The goal of this phase is to transform the requirement specification into astructure that is suitable for implementation in some programming language.

oImplementation and unit testing During this phase the design is implemented. Initially small modules aretested in isolation from rest of the software product. oIntegration and system testing

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 70

In this all the modules are integrated and then tested altogether. oOperation and maintenance. Release of software inaugurates the operation and life cycle phase of theoperation.The phases always occur in this order and do not overlap. 10.2.3. Software Requirement Specification (SRS) 1. Introduction: The following subsections of the SRS document provide an overview of theentire SRS. i) Purpose: The purpose of the project is to provide online facility to Expert or Instituteto conduct online exams and to Students to give online exams. Expert can enter andedit the questions. Also they can view the result. Studentscan login and give their respective exams and view their score then and there. Otherscan view sample papers to get look and feel of the online examination system. ii) Scope: The website to conduct online examination is OnlineExaminamtion. Thiswebsite provides facility to Expert/Instituteto conduct online exams by providing a uniqueid to each Expert/Institute. The Expert/institute provides questions marks. In turn student can login with their id to give the examsand can view their result then and there. Benefits: This website reduces the manual work, maintaining accuracy, increasingefficiency and saving time. Also institutes need not go to develop a newsoftwareeach time, instead they just register and conduct a test. For students, it saves time ofgoing to far away centers and also they can view their result then and there. iii) Abbreviations: JSP stands for Java Server Pages, HTTP stands for HyperText Transfer Protocol iv) References: IEEE Recommended Practice for Software Requirements SpecificationIEEE Std 830-1993.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 71

v) Overview: The rest of this SRS document describes the various systemrequirements, interfaces, features and functionalities in detail.

2. Overall Description: In Online examination system Expert institute can register to conducta online test and view the records later. Students can give the test and their respective records, which include their marks for each test given by them, will be maintainedseparately. No student can take a particular exam more than once. i.) ProductPerspective: (i) User interfaces The application will have a user friendly and menu based interface.Following screens will be provided: (a) A login screen for entering the username, password will beprovided. Access to different screens will be based upon the user. (b) There is a screen for displaying information regarding entries to bemade by institutes.
(c) There is a screen for displaying information regarding filling ofexam details by institutes. (d) There is a screen for displaying information regarding enteringstudent list for the particular exam. (e) There is a screen for displaying information menu regarding whatoptions the institutes will select while filling entries(enteringquestions, student list, deleting questions, entering exam (details). (f) There is a screen for displaying exam details to the students whenthey are taking exams. (g) There is a screen for taking exam for the students. (h) There is a screen for displaying of results of students after takingthe exam. (ii) Hardware interfaces (i) Support for printer for printing results then and there. (ii) Screen resolution of at least 800X600 is required for proper andcomplete viewing of screens. Higher resolution will be accepted.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 72

(iii) Software interfaces (i) Any windows based operating system. (ii) MS-Access 2000 as the DBMS for database. (iii) IDE (NET BEANS) for developing code. (iv) Communications interfaces None (v) Memory Constraints At least 512 MB RAM and 5 MB space on hard disk will be required forrunning the application. (x) Site Adaptation Requirements Web browser with cookies enabled.

ii.) Product Functions:


The website will allow access only to authorized users withspecific roles (Administratormaintains the website, Institutes-Register to conduct theexams, Students-Give the exams online) A summary of the major functions that the website will perform: a. Provide facility to Expert/institutes to register to conduct a online test. b. Expert/Institutes can enter the number of questions, with marks,questions and answers c. Students can login and give the tests.

iii.) User Characteristics:


a. Educational level: Users should be comfortable with the Englishlanguage. b. Experience: Users should have prior information regarding the onlineexaminations. c. Skills: Users should have basic knowledge and should be comfortableusing general purpose applications on computers.

iv.) Constraints:

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 73

* Since the DBMS being used is MS Access 2000, which is not a verypopular DBMS, it will not be able to store a very huge number ofrecords. * Due to limited features of DBMS being used performance tuningfeatures will not be applied to the queries and thus the system maybecome slow with the increase in number of records being stored. * An extra security as SSL must be used to secure the marks details andother examination information.

v.) Assumptions:
The examinations are all objective. Students can give eachexam just once.

vi) Apportioning of Requirements:


The future versions of the website willbe having a better database to handle larger number of records, in a more secure way.

3. Specific Requirements: This section provides software requirements to alevel of detail sufficient to enable designers to design the system andtesters to test the system.

External Interface Requirements:

User Interfaces: Student Registration Screen:Various fieldsavailable on this screen will be:

Use id Password

Expert/Institute Login Screen: Fields available on thisscreen are:


Expert id Password

Entering Questions: Various Fields are:


Questions Options (4) Correct Answer

Exam Details Screen: Various Fields are:


Paper Id No. Of Questions Time Limit


Page 74

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Student Login Screen: Various Fields are:


Student ID Update profile Available test Upload Photo View Result

Student Taking Exam Screen: Various Fields are:


Test Paper Category List View Test Select test Start Test

Result Displaying Screen: Various Fields are:


No. Of Correct Questions Correct Answer with Description Get marks

Hardware interfaces:

Support for printer for printing resultsthen and there. Screen resolution of at least 800X600 is required for properand complete viewing

of screens. Higher resolution will beaccepted. Software interfaces:


Any windows based operating system. MS Access 2000 as the DBMSfor database. IDE (NET BEANS) for developing code.

Communications interfaces

None

ii.)Software Product Features: Validity Checks: Java-script provides validity checks forvarious fields in the forms. Sequencing Information: All the informationregarding exam details, student list, question details,display of result should be handled sequentially thatis data should be stored only in a particularsequence to avoid any inconvenience. Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)
Page 75

Error Handling: If any of the validations orsequencing flows does not hold true thenappropriate error messages will be prompted to theuser for doing the needful. iii.) Performance Requirements: This subsection specifies numericalrequirements placed on the software or on the human interaction with thesoftware, as a whole. Numerical requirements will include: *300 terminals will be supported at a time *Only text information will be supported(HTTP) *All the transactions will be processed within seconds. iv.) Design Constraints: None v.) Software System Attributes: Security: Only authorized users will be able to access the website by entering thecorrect login name and corresponding password. Maintainability: The website can be maintained in present or future. It will be easy toincorporate new requirements in the individual modules. Portability: As the website is online so will be easily portable on various systems.The website will be also easily portable on any windows based system that has MS-ACCESSinstalled.

vi.)Logical Database Requirements: The following information will be placedin the database:
User Master :-uid , Uname , Password, address, contact, email ,Dob, quali gender , mstatus. Category Master :-catid , catname . Expert Master :-eid, ename , Password, address, contact, email ,Dob, catid, quali gender , mstatus.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 76

Question Master:-qid, question,option1,option2, option3, option4,ansdes, answer, level, catid, eid. Test Master:-tid, catid, testdate, duration, nquestion, marks, level.

Vii Other Requirements:None

10.3. OVERVIEW OF PROJECT :


The online test created for taking online test has following stages: _ Login _ Test _ Result Login: There is a quality login window because this is more secure than otherlogin forms as in a normal login window there are multiple logins availableso that more than one person can access to test with there individual login.But in this project there is only one login id i.e. administrator id andpassword by which a person enter the site. Hence it is more secure andreliable than previously used on-line test simulators. Test: Test page is the most creative and important page in this project. Itconsists of 2 modules namely: _ Subject selection _ Utilities Subject selection: From the given choices the candidate can select hisfield (like programming and Networking etc) for taking on with the test. Utilities:

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 77

It includes: _ CannotSkip and come back to the question afterwards ifneeded. _ Gives the Answer Description with correct answer .

TECHNOLOGIES USED: Front end as:HTML Back end as:Advance Java Server:Apache tomcat 6.0 Database:Microsoft access Querying language:Sql

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 78

10.4 Documentation:
10.4.1 Use-case Diagram:

Figure-10.1: Use Case Diagram

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 79

10.4.2 Data flow Diagram(DFD):

Figure-10.2: Data flow Diagram(DFD)

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 80

10.4.3: Data flow Diagram(DFD-1):

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 81

10.4.3Entity relationshipDiagram (E-R diagram):

Figure-10.3:E-R diagram

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 82

10.5. Feasibility Study


Once scope has been identified (with the concurrence of the customer), it isreasonable to ask: Can we build software to meet this scope? Is the projectfeasible? All too often, software engineers rush past this questions (or arepushed past them by impatient managers or customers), only to becomemired in a project that is doomed from the onset. When we are developing the system (software), we must know the proposedsystem will be feasible or i.e. practically implemented or not it may possiblethe proposed( candidate ) system may not implemented due to many reasonslike it may take long time in development than the specified time limit ,costmay increase than proposed one etc. Therefore we must analyze thefeasibility of the system. Feasibility is the analysis of risks, costs & benefits relating to economics,technology & user operation.There are several types of feasibility depending on the aspect they covers. Some important feasibility is as follows:MS-Access database will be used for storing data.Hardware requirements used are compatible with all O.S. Only authorizedperson would be able to use the (I) Technical Feasibility (II) Operational Feasibility (III) Economical Feasibility Technical Feasibility:The technically feasibility study basically centers on alternatives forhardware, software and design approach to determine the functional aspectsof system.This project on Online Examination will be platform independent since it isbeing coded in JAVA language (using JSP and SERVLETS).HTML is usedto create web pages.website so it would be secure. The systemcan also be expanded as per the needs of requirement specification. Operational Feasibility:Operational Feasibility is a measure of how people are able to work withsystem. This type of feasibility demands if the system will work whendeveloped and installed.Since website is very user friendly so users will find it comfortable to workon this site.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 83

Economical Feasibility:Economic analysis is the most frequently used evaluating the effectivenessof proposed system, more commonly known as Benefit analysis. The Benefitanalysis is to determine benefits and savings which are expected fromcandidate system and compare them with cost. If the benefits are more thanthe cost, then decision is made to design and implement the system. The costand benefits may be direct or indirect and tangible or intangible. Testing:Software testing is the process of executing a program with intension of finding errors inthe code. It is a process of evolution of system or its parts by manual or automatic meansto verify that it is satisfying specified or requirements or not.Generally, no system is perfect due to communication problems between user anddeveloper, time constraints, or conceptual mistakes by developer. To purpose of system testing is to check and find out these errors or faults as early aspossible so losses due to it can be saved.Testing is the fundamental process of software success. Testing is not a distinct phase in system development life cycle but should be applicablethroughout all phases i.e. design development and maintenance phase.Testing is used to show incorrectness and considered to success when an error isdetected.

10.6. Objectives Of Software Testing


The software testing is usually performed for the following objectives: Software Quality Improvement:The computer and the softwareare mainly used for complex and critical applications and a bug or fault in softwarecauses severe losses. So a great consideration is required for checking for quality ofsoftware. Verification And Validation:Verificationmeans to test that we are building the product in right way .i.e. arewe using the correct procedure for the development of software so that it can meetthe user requirements. Validationmeans to check whether we are building the right product or not.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 84

Software Reliability Estimation:The objective is to discover theresidual designing errors before delivery to the customer. The failure data during processare taken down in order to estimate the software reliability.

10.7. Principles Of Software Testing


Software testing is an extremely creative and challenging task. Some important principlesof software testing are as given: All tests should be traceable to customer requirements. Testing time and resources should be limited i.e. avoid redundant testing. It is impossible to test everything. Use effective resources to test. Test should be planned long before testing begins i.e. after requirement phase. Test for invalid and unexpected input conditions as well as valid conditions. Testing should begin in in the small and progress towards testing in the large. For the most effective testing should be conducted by an independent party. Keep software static (without change mean while) during test. Document test cases and test results. Examining what the software not doing which it expected to do and also checking what it is doing that was not expected to do.

10.8. Strategy For Software Testing


Different levels of testing are used in the test process; each level of testing aims to test differentaspects of the system. The first level is unit testing. In this testing, individual components are tested toensure that they operate correctly. It focuses on verification efforts. The second level is integration testing. It is a systematic technique for constructingthe program structure. In this testing, many tested modules are combined into thesubsystem which are then tested. The good here is to see if the modules can beintegrated properly. Third level is integration testing. System testing is actually a series of different testswhose primary purpose is to fully exercise computer based system. These tests

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 85

falloutside scope of software process and are not conducted solely by software engineers.

10.9. Application home page :


It Is the Home Window Of the Online Examination System In which There Are Six HTML Pages , Which names are as follows: Home Student Institute About us Help/ faq Contact us By clicking On the Sample exam or Sample Online Test The Student and Expert Can Redirect to the Online Examination Window.

figure 10.3 Application Home Window

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 86

10.10. Application Login Window


It is the Sign in window By which Expert and Student can Log in if they have already Their own id but if they have not than the will be Sign up before Sign-in .

Figure 10.4 Sign in window

10.11 Window after Sign in:


After Sign in Both Student and Expert the window will be different which as follows : 10.11.1 After Sign in of Student : It is the window which will be show after Sign in of Student. Which have mainly four parts namely as: _ Update profile

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 87

_Available Tests _Upload Photo _View Results

Figure 10.5Window After Sign in Of Student

10.11.2 After Sign in of Expert : It is the window which will be show after Sign in of Expert . Which have mainly four parts namely as: _ Expert Galary _Submit New Question _Generate New Test Paper _Update My Profie

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 88

Figure-10.6: Window After Sign in Of Expert

10.12Test Paper Category:

Figure-10.7:Test Paper category

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 89

10.13 Question Of Programming Test :

Figure-10.8: Question window Of Programming test

10.14Student Result with Correct Answer and Description:

Figure-10.9: Student result window with answer and Description

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 90

10.15 Student All Tests Results:

Figure-10.10: window of Student All test results

10.16 Student Certificate:

Figure-10.11: window of Student certificate

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 91

CONCLUSION
The On line exam System is developed using Java and sql fully meets the objectives of the system for which it has been developed. The system has reached a steady state where allbugs have been eliminated. The system is operated at a high level of efficiency and all the teachers and user associated with the system understands its advantage. The system solves the problem. It was intended to solve as requirement specification.

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 92

REFRENCES

Website:www.google.com
www.wikipedia.com

Books:Head first java


Java 2(complete reference)

Laxmi devi Institute Of Engineering And Technology, Alwar (Raj.)

Page 93

S-ar putea să vă placă și