+ All Categories
Home > Documents > Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the...

Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the...

Date post: 15-Jun-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
33
Jawaharlal Nehru Engineering College Laboratory Manual Web Information System For Final Year Students Dept: Information Technology
Transcript
Page 1: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Jawaharlal Nehru Engineering College

Laboratory Manual

Web Information System

For

Final Year Students

Dept: Information Technology

Page 2: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

FOREWORD

It is my great pleasure to present this laboratory manual for Final Year engineering

students for the subject of Web Information System keeping in view the vast coverage required

for Programming with Java Language

As a student, many of you may be wondering with some of the questions in your mind

regarding the subject and exactly what has been tried is to answer through this manual.

As you may be aware that MGM has already been awarded with ISO 9000 certification

and it is our endure to technically equip our students taking the advantage of the procedural

aspects of ISO 9000 Certification.

Faculty members are also advised that covering these aspects in initial stage itself, will

greatly relived them in future as much of the load will be taken care by the enthusiasm energies

of the students once they are conceptually clear.

Dr. S.D.Deshmukh

Principal

Page 3: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Vision of JNEC

College seeks to be the engineering college of choice in Maharashtra that

can provide the best learning experience, the most productive learning community, and the most creative learning environment in Engineering Education and will be recognized as one of the best Engineering Colleges

in India.

Mission of JNEC

To develop innovative engineers with human values, well equipped to solve complex technical problems, address the needs of modern society and pursue lifelong learning, by providing them competent, caring and

committed faculty. IT Vision:

IT department is committed to ensure the quality education to students’

by providing innovative resources & continuous up-gradation of the department. To achieve “Heights of Excellence” in the world we strive to

organize regular interaction with Industry and Alumni. IT Mission:

To impart core technical competency & knowledge in students through

curriculum and certification programs to fulfill the industry requirements which ultimately benefits society at large.

Program Educational Objectives:

I. Preparation: To prepare students to excel in PG program or to succeed in Industry /Technical profession through global, rigorous education.

II. Core Competence: To provide students with a solid foundation in mathematical, scientific and engineering fundamentals required to

solve engineering problems and also to pursue higher studies. III. Breadth: To train students with good scientific and engineering

breadth so as to comprehend, analyze, design and create novel

product and solution for the real life problems. IV. Professionalism: To inculcate in students’ professional and ethical

attitude, effective communication skills, team work skills, multi-disciplinary approach and an ability to relate engineering issues to broader social context.

V. Learning Environment: To provide students with academic environment aware of excellence, leadership, written ethical codes and guidelines and lifelong learning needed for successful

professional career.

Page 4: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

LABORATORY MANUAL CONTENTS

This manual is intended for the Final Year students of Information Technology in the

subject of Web Information System. This manual typically contains practical/Lab Sessions

related advanced Programming in Java covering various aspects related the subject to enhanced

understanding.

As per the syllabus along with Study of Java Language, we have made the efforts to

cover various aspects of Web Information System covering different Techniques used to

construct and understand concepts of advance Java Programming.

Students are advised to thoroughly go through this manual rather than only topics

mentioned in the syllabus as practical aspects are the key to understanding and conceptual

visualization of theoretical aspects covered in the books.

Good Luck for your Enjoyable Laboratory Sessions

Prof. S.N. Jaiswal

Head IT Dept.

Page 5: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

DOs and DON’Ts in Laboratory:

1. Make entry in the Log Book as soon as you enter the Laboratory.

2. All the students should sit according to their roll numbers starting from their left to right.

3. All the students are supposed to enter the terminal number in the log book.

4. Do not change the terminal on which you are working.

5. All the students are expected to get at least the algorithm of the program/concept

to be implemented.

6. Strictly observe the instructions given by the teacher/Lab Instructor.

Instruction for Laboratory Teachers::

1. Submission related to whatever lab work has been completed should be done during the next

lab session. The immediate arrangements for printouts related to submission on the day of

practical assignments.

2. Students should be taught for taking the printouts under the observation of lab teacher.

3. The promptness of submission should be encouraged by way of marking and evaluation

patterns that will benefit the sincere students.

Page 6: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

SUBJECT INDEX

1. Study of Java 2 Platform, Enterprise Edition.

2. Introduction to Servlet.

3. Program to display request header information.

4. Program to perform database operations.

5. Study of cookies.

6. Program for session tracking.

7. Program to design an application using JSP, Servlet, and My-SQL.

8. Program to create custom tags.

9. Program to apply validations using Java Script.

10. Mini project using JSP, Servlet, Ajax, and My-SQL.

Page 7: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

1. Java 2 Platform, Enterprise Edition

Aim: Study of Java 2 Platform, Enterprise Edition.

Theory:

J2EE (Java 2 Platform, Enterprise Edition)

J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the

mainframe-scale computing typical of large enterprises. Sun Microsystems (together with

industry partners such as IBM) designed J2EE to simplify application development in a

thin client tiered environment. J2EE simplifies application development and decreases

the need for programming and programmer training by creating standardized, reusable

modular components and by enabling the tier to handle many aspects of programming

automatically.

J2EE includes many components of the Java 2 Platform, Standard Edition (J2SE):

The Java Development Kit (JDK) is included as the core language package.

Write Once Run Anywhere technology is included to ensure portability.

Support is provided for Common Object Request Broker Architecture (CORBA),

a predecessor of Enterprise JavaBeans (EJB), so that Java objects can

communicate with CORBA objects both locally and over a network through its

interface broker.

Java Database Connectivity 2.0 (JDBC), the Java equivalent to Open Database

Connectivity (ODBC), is included as the standard interface for Java databases.

A security model is included to protect data both locally and in Web-based

applications.

J2EE also includes a number of components added to the J2SE model, such as the

following:

Full support is included for Enterprise JavaBeans. EJB is a server-based

technology for the delivery of program components in an enterprise environment.

It supports the Extensible Markup Language (XML) and has enhanced deployment

and security features.

The Java servlet API (application programming interface) enhances consistency

for developers without requiring a graphical user interface (GUI).

Page 8: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Java Server Pages (JSP) is the Java equivalent to Microsoft's Active Server Pages

(ASP) and is used for dynamic Web-enabled data access and manipulation.

The J2EE architecture consists of four major elements:

The J2EE Application Programming Model is the standard programming model

used to facilitate the development of multi-tier, thin client applications.

The J2EE Platform includes necessary policies and APIs such as the Java servlets

and Java Message Service (JMS).

The J2EE Compatibility Test Suite ensures that J2EE products are compatible

with the platform standards.

The J2EE Reference Implementation explains J2EE capabilities and provides its

operational definition.

Container Types

The deployment process installs J2EE application components in the J2EE

containers illustrated in following fig.

Figure: J2EE Server and Containers

J2EE server

Page 9: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

The runtime portion of a J2EE product. A J2EE server provides EJB and Web

containers.

Enterprise JavaBeans (EJB) container Manages the execution of enterprise beans for J2EE applications. Enterprise beans

and their container run on the J2EE server.

Web container Manages the execution of JSP page and servlet components for J2EE applications.

Web components and their container run on the J2EE server.

Application client container Manages the execution of application client components. Application clients and

their container run on the client.

Applet container Manages the execution of applets. Consists of a Web browser and Java Plug-in

running on the client together.

Conclusion : Hence we have studied Java 2 Platform, Enterprise Edition.

Journal Write Up: - Introduction to Java 2 Platform, Enterprise Edition

- Web servers

- J2EE Architecture

- J2EE Containers

Page 10: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

2. Introduction to Servlet

Aim: Write a program to demonstrate Basic Servlet.

Theory: As we know that the servlet extends the HttpServlet and overrides the doGet ()

method which it inherits from the HttpServlet class. The server invokes doGet () method

whenever web server receives the GET request from the servlet. The doGet() method

takes two arguments first is HttpServletRequest object and the second one is

HttpServletResponse object and this method throws the ServletException.

Whenever the user sends the request to the server then server generates two

objects’ first is HttpServletRequest object and the second one is HttpServletResponse

object. HttpServletRequest object represents the client's request and the

HttpServletResponse represents the servlet's response.

Inside the doGet() method our servlet has first used the setContentType() method

of the response object which sets the content type of the response to text/html It is the

standard MIME content type for the html pages.After that it has used the method

getWriter () of the response object to retrieve a PrintWriter object. To display the output

on the browser we use the println () method of the PrintWriter class.

Program

Import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class hello extends HttpServlet

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<body>");

out.println("<h1 align=center>Basic servlet program</h1>");

out.println("</body>");

Page 11: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

out.println("</html>");

Output:

Conclusion: Hence we studied how to create a sample servlet to display date and the time.

Journal Write-up: - HTTP protocol & its methods

- Introduction to servlet

- Servlet configuration

- Life cycle of servlet

- Requests and Responses

Additional List of Programs :

1. WAP to display the username using servlet

2. WAP to design the login form using servlet.

3. Write a servlet program for customer registration.

4. WAP to design Tech Support Application which involves:

- Collecting a technical support request

- Storing the support request in a database

- Generating a confirmation page

Page 12: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

3. Request Header

Aim:- Display request header information.

Theory:

Reading Request Headers

Reading headers is straightforward; just call the getHeader method of Http-

ServletRequest with the name of the header. This call returns a String if the specified

header was supplied in the current request, null otherwise. In HTTP 1.0, all request

headers are optional; in HTTP 1.1, only Host is required. So, always check for null before

using a request header.

Header names are not case sensitive. So, for example, request.get-

Header("Connection") i s interchangeable with request.get-Header("connection").

Although getHeader is the general-purpose way to read incoming headers, a few

headers are so commonly used that they have special access methods in Http-

ServletRequest. Following is a summary.

• getCookies

The getCookies method returns the contents of the Cookie header, parsed

and stored in an array of Cookie objects. This method is discussed in more detail

in Chapter 8 (Handling Cookies).

• getAuthType and getRemoteUser

The getAuthType and getRemoteUser methods break the Authorization

header into its component pieces.

• getContentLength

The getContentLength method returns the value of the Content-Length

header (as an int).

• getContentType

The getContentType method returns the value of the Content-Type header

(as a String).

• getDateHeader and getIntHeader

The getDateHeader and getIntHeader methods read the specified headers

and then convert them to Date and int values, respectively.

• getHeaderNames

Page 13: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Rather than looking up one particular header, you can use the

getHeaderNames method to get an Enumeration of all header names received on

this particular request.

• getHeaders

In most cases, each header name appears only once in the request.

Occasionally, however, a header can appear multiple times, with each occurrence

listing a separate value. Accept-Language is one such example. You can use

getHeaders to obtain an Enumeration of the values of all occurrences of the

header.

Program:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Request Header</title>

</head>

<body >

<font size="+2" color="green">Information about request header</font>

<br>

<table style="background-color: white; border-color: black; width: 50%"

border="2" >

<tr>

<th> Method used to send request </th>

<td> <%=request.getMethod()%> </td>

</tr>

<% java.util.Enumeration names=request.getHeaderNames();

while(names.hasMoreElements())

String hname=(String)names.nextElement();

%>

<tr>

<th> <%= hname %> </th>

<td> <%= request.getHeader(hname)%> </td>

</tr>

<%

%>

Page 14: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

</table>

</body>

</html>

Output

Conclusion: Hence we have performed program for request header.

Journal Write-up:

- Introduction to request header

- Understanding request header

1. Accept

2. Accept-Charset

3. Accept-Encoding

Page 15: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

4. Accept-Language

5. Authorization

6. Connection

7. Content-Length

8. Cookie 9. Host 10. User-Agent

4. Database operations

Aim: WAP to design web application.

Theory:

Inserting Data in Database table using Statement

In this program we are going to insert the data in the database from our java program

in the table stored in the database.

To accomplish our goal we first have to make a class named as

ServletInsertingData, which must extends the abstract HttpServlet class, the name of

the class should be such that other person can understand what this program is going to

perform. The logic of the program will be written inside the doGet() method that takes

two arguments, first is HttpServletRequest interface and the second one is the

HttpServletResponse interface and this method can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can

insert the data in the database only and only if there is a connectivity between our

database and the java program. To establish the connection between our database and the

java program we first need to call the method forName(), which is static in nature of the

class Class. It takes one argument which tells about the database driver we are going to

use. Now use the static method getConnection() of the DriverManager class. This

method takes three arguments and returns the Connection object. SQL statements are

executed and results are returned within the context of a connection. Now your

connection has been established. Now use the method createStatement() of the

Connection object which will return the Statement object. This object is used for

executing a static SQL statement and obtaining the results produced by it. We have to

insert a values into the table so we need to write a query for inserting the values into the

table. This query we will write inside the executeUpdate() method of the Statement

object. This method returns int value.

If the record will get inserted in the table then output will show "record has been

inserted" otherwise "sorry! Failure".

Page 16: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Program

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class DataInsertion extends HttpServlet

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String url = "jdbc:mysql://localhost/zulfiqar?user=root&password=admin";

Connection conn;

ResultSet rs;

try

Class.forName("org.gjt.mm.mysql.Driver");

conn = DriverManager.getConnection(url);

Statement statement = conn.createStatement();

String query = "insert into emp_sal values('Rajesh', 15000)";

int i = statement.executeUpdate(query);

if(i!=0)

out.println("The record has been inserted");

else

out.println("Sorry! Failure");

rs = statement.executeQuery("select * from emp_sal");

while(rs.next())

out.println("<p><table>" + rs.getString(1) + " "

+ rs.getInt(2) + "</p></table>");

rs.close();

statement.close();

Page 17: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

catch (Exception e)

System.out.println(e);

Table in the database before Insertion:

mysql> select * from emp_sal;

Empty set (0.02 sec)

The output of the program is given below:

Table in the database after Insertion:

mysql> select * from emp_sal;

+----------+--------+

| EmpName | salary |

+----------+--------+

| Rajesh | 15000 |

+----------+--------+

1 row in set (0.02 sec)

Conclusion: Hence we have designed web application using My Sql.

Rajesh

Page 18: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Journal Write up:

5. Study of Cookies

Aim: WAP for cookies.

Theory:

Cookies

Also known as browser cookies or tracking cookies, cookies are small, often

encrypted text files, located in browser directories. They are used by web developers to

help users navigate their websites efficiently and perform certain functions. Due to their

core role of enhancing/enabling usability or site processes, disabling cookies may prevent

users from using certain websites.

Cookies are created when a user's browser loads a particular website. The website

sends information to the browser which then creates a text file. Every time the user goes

back to the same website, the browser retrieves and sends this file to the website's server.

Computer Cookies are created not just by the website the user is browsing but also by

other websites that run ads, widgets, or other elements on the page being loaded. These

cookies regulate how the ads appear or how the widgets and other elements function on

the page.

Cookie Class

In JSP cookie is the object of the class javax.servlet.http.Cookie. This class is

used to create a cookie, a small amount of information sent by a servlet to a Web

browser, saved by the browser, and later sent back to the server. A cookie's value can

uniquely identify a client, so cookies are commonly used for session management. A

cookie has a name, a single value, and optional attributes such as a comment, path and

domain qualifiers, a maximum age, and a version number.

The getCookies() method of the request object returns an array of Cookie objects.

Cookies can be constructed using the following code:

Cookie (java.lang.String name, java.lang.String value)

Page 19: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Cookie objects have the following methods.

Method Description

getComment() Returns the comment describing the purpose of this

cookie, or null if no such comment has been defined.

getMaxAge() Returns the maximum specified age of the cookie.

getName() Returns the name of the cookie.

getPath() Returns the prefix of all URLs for which this cookie is

targeted.

getValue() Returns the value of the cookie.

setComment(String) If a web browser presents this cookie to a user, the

cookie's purpose will be described using this comment.

setMaxAge(int)

Sets the maximum age of the cookie. The cookie will

expire after that many seconds have passed. Negative

values indicate the default behavior: the cookie is not

stored persistently, and will be deleted when the user web

browser exits. A zero value causes the cookie to be

deleted

setPath(String) This cookie should be presented only with requests

beginning with this URL.

setValue(String)

Sets the value of the cookie. Values with various special

characters (white space, brackets and parentheses, the

equals sign, comma, double quote, slashes, question

marks, the "at" sign, colon, and semicolon) should be

avoided. Empty values may not behave the same way on

all browsers.

Program: /* Display path of the cookie */

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ReadCookies extends HttpServlet

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException

Page 20: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Cookie cookie = null;

boolean newCookie = false;

if (cookie == null)

newCookie = true;

cookie = new Cookie("Cookies", "" + getNextCookieValue());

cookie.setPath(request.getContextPath());

response.addCookie(cookie);

response.setContentType("text/html");

java.io.PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head>");

out.println("<title>Read Cookie</title>");

out.println("</head>");

out.println("<body>");

out.println("<h2> Our Cookie named \"Cookies\"information</h2>");

if (newCookie)

out.println("Cookie Path: " + cookie.getPath() + "<br>");

out.println("</body>");

out.println("</html>");

out.close();

private long getNextCookieValue()

return new java.util.Date().getTime();

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException

doGet(request, response);

Output

Page 21: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Conclusion: Hence we have performed the program for cookies.

Journal Write-up:

- Introduction to cookies

- Types of cookie

- Different methods used to perform operations on cookies

Additional List of Programs :

1. WAP to display cookie value, cookie age and cookie path.

2. WAP in JSP file to set and then display the cookie.

3. WAP to create and store value of cookie.

Cookie Path: /Cookies11

Page 22: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

6. Session Tracking

Aim: Study of session tracking

Theory:

Session

A session is a conversation between the server and a client. A conversation

consists of series of continuous request and response.

When there is a series of continuous request and response from a same client to a

server, the server cannot identify from which client it is getting requests. Because HTTP

is a stateless protocol.

When there is a need to maintain the conversational state, session tracking is

needed. For example, in a shopping cart application a client keeps on adding items into

his cart using multiple requests. When every request is made, the server should identify in

which client’s cart the item is to be added. So in this scenario, there is a certain need for

session tracking.

Solution is, when a client makes a request it should introduce itself by providing

unique identifier every time. There are five different methods to achieve this.

Session tracking methods:

1. User authorization

2. Hidden fields

3. URL rewriting

4. Cookies

Page 23: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

5. Session tracking API

Program

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

public class SessionTracker extends HttpServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

response.setContentType("text/html");

PrintWriter out=response.getWriter();

HttpSession session=request.getSession(true);

Integer count=(Integer)session.getValue("tracker.getCount");

if(count==null)

count=new Integer(1);

else

count=new Integer(count.intValue()+1);

session.putValue("tracker.count",count);

out.println("<html><head><title>Session Tracker</title></head>");

out.println("<body><h1>Session tracking demo</h1>");

out.println("you have visited this page"+count+((count.intValue()==1)?

"time":"times:"));

out.println("<p>");

out.println("<h2>Here is your session data:</h2>");

String[] names=session.getValueNames();

for(int i=0;i<names.length;i++)

out.println(names[i]+":"+session.getValue(names[i])+"<br>");

out.println("</body></html>");

Output:

Page 24: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Conclusion: Hence we have performed program for session tracking.

Journal Write-up:

- Introduction to session

- Session tracking methods

- The session life cycle

Additional List of Programs :

- Demonstrate session life cycle with cookies.

- WAP to demonstrate the methods for managing the state in the HttpSession.

- WAP to design simple shopping cart using sessions.

Page 25: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

8. Custom Tags

Aim: - WAP to create Custom tags

Theory:

Custom Tag

A custom tag is a user-defined JSP language element. When a JSP page containing

a custom tag is translated into a servlet, the tag is converted to operations on an object

called a tag handler. The Web container then invokes those operations when the JSP

page's servlet is executed.

Custom tags have a rich set of features. They can

Be customized via attributes passed from the calling page.

Access all the objects available to JSP pages.

Modify the response generated by the calling page.

Communicate with each other. You can create and initialize a JavaBeans

component, create a variable that refers to that bean in one tag, and then use the

bean in another tag.

Be nested within one another, allowing for complex interactions within a JSP

page.

Page 26: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

The technique for reducing the amount of Java code in a JSP is to use custom tags. A

custom tag is really considered a JSP action element, because it uses the same syntax.

They perform some type of action that you define. The benefit of custom tags is that you

can provide powerful features in your JSP without exposing the page to a lot of Java

code. Custom tags facilitate the separation of business logic from presentation logic.

The Java code that actually does the work of the custom tag is contained in a tag

library that you create. The tag library contains what some refer to as "tag handlers,"

which are simply Java programs that use some special servlet tag classes. The JSP

developer doesn't have to deal with the code, but instead deals with an easy-to-understand

XML-formatted tag statement.

The Custom Tag Library Architecture To help you understand how custom tags work, examine the illustration in Fig.1.

Page 27: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Fig 1: Custom tags include the JSP, the tag library descriptor, and the tag

library

Program: 1.CustomTag.java

package custompkg;

import javax.servlet.annotation.WebServlet;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

@WebServlet(name = "CustomTag", urlPatterns = "/CustomTag")

public class CustomTag extends TagSupport

/* Invokes when the start tag of the custom tag is encountered */

public int doStartTag() throws JspException

try

Page 28: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

JspWriter out=pageContext.getOut();

out.println("<BR><B>Copyright RoseIndia Technologies<B>");

catch (Exception IOException)

System.err.println("IO Exception");

System.err.println("ioException.toString()");

/* Returning the SKIP_BODY, as the body content is not be evaluated */

return SKIP_BODY;

/* Invokes when the end tag of the custom tag is encountered */

public int doEndTag() throws JspException

/* Skip the processing of the rest of the page */

return SKIP_PAGE;

2. newtag_library.tld

<?xml version="1.0" encoding="UTF-8"?>

<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">

<tlib-version>1.0</tlib-version>

<short-name>newtag_library1</short-name>

<uri>/WEB-INF/tlds/newtag_library1</uri>

<tlib-version>1.0</tlib-version>

<jsp-version>1.2</jsp-version>

<short-name>Copyright Info</short-name>

<uri>/newtag_library1.tld</uri>

<description>

Developing First Custom Tags

</description>

<tag>

<name>CTag</name>

<tag-class>custompkg.CustomTag</tag-class>

<body-content>empty</body-content>

</tag>

Page 29: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

</taglib>

3.index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1 align="center"> <font color="blue">Web Information System </font></h1>

<font color="red"><h2 align="center"> JSP custom tags</h2>

<%@taglib uri="/WEB-INF/tlds/newtag_library1" prefix="CTag" %>

<chrt:CustomTag />

</font>

</body>

</html>

Output:

Conclusion:

Hence we have performed program to create custom tags.

Page 30: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Journal Write-up:

- Introduction to custom tags

- JSP

- The taglib Directive

- The Tag Library

- The Tag Library Descriptor

- Tag Library Deployment

9. Java Script Validations

Page 31: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

Aim: - WAP for Java script validation.

Theory:

Java Server Pages

Java Server Pages (JSP) is a java technology that allows software developer to

dynamically generate a HTML, XML or other types of the documents in response to a

web client request. The technology allows java code and certain predefined actions to be

embedded into static content.

The jsp syntax adds additional XMLlike tags, called JSP action, to be used to

invoke built in functionality dynamically generate .Additionally the technology allows us

for the creation of the jsp tags libraries that acts as a extension to the standard HTML or

XML tags. Tag libraries provide the platform independent way of extending the

capabilities of a web server.

JSP are compiled into the java servlet by the java compiler. A jsp compiler may

generate a servlet in java code that is then compiled by the java compiler. JSP technology

may enable the web developer and designers to rapidly develops and easily maintain,

information rich, dynamic web pages that leverage existing business system.

This simple page contains plain HTML, except for couple of the JSP directives

and tags. The first one in the HelloWorld.jsp is a page directive that defines the content

type and character set of the entire page. Java method println () to print output. By this

example we are going to learn that how can you write a jsp program on your browser.

This program also contains HTML (Hypertext Markup Language) code for

designing the page and the contents. Following code of the program prints the string

"Hello World!" by using <%="Hello World!" %> while you can also print the string by

using out.println ().

Java Script Validations

The idea behind JavaScript form validation is to provide a method to check the

user entered information before they can even submit it. JavaScript also lets you display

helpful alerts to inform the user what information they have entered incorrectly and how

they can fix it. In this lesson we will be reviewing some basic form validation, showing

you how to check for the following:

• If a text input is empty or not

• If a text input is all numbers

• If a text input is all letters

• If a text input is all alphanumeric characters (numbers & letters)

• If a text input has the correct number of characters in it (useful when restricting

the length of a username and/or password)

• If a selection has been made from an HTML select input (the drop down selector)

• If an email address is valid

Program <html>

Page 32: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript">

function validate(field,alerttxt)

with(field)

if(value==null||value=="")

alert(alerttxt);

return false;

else

return true;

function validate_form(thisform)

with(thisform)

if(validate(email,"email must be filled out!")==false)

email.focus();

return false;

</script>

</head>

<body>

<h1>Required Field Validation</h1><br/>

<form name="form1" action="valid.html" onsubmit="return validate_form(this) "

method="post">

Email: <input type="text" name="email" size="30">

<input type="submit" value="Submit">

</form>

Page 33: Laboratory Manual - Jawaharlal Nehru Engineering College lab manual.pdf · 6. Strictly observe the instructions given by the teacher/Lab Instructor. Instruction for Laboratory Teachers::

</body>

</html>

Output

Conclusion: Hence we have performed the program for java script validations.

Journal Write-up:

- Introduction to JSP

- Java script form validations

Additional List of Programs :

1. WAP to design an application and apply all java script form validations.

.


Recommended