Lab - Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

LAB MANUAL

INDEX

1. Demonstrate use of URL Class, URLConnection And InetAddress.

2. Chat Application Using TCP and UDP (DatagramSocket, DatagramPacket


class,Socket, ServerSocket)

3. Program to illustrate DatagramSocket , DatagramPacket

4. JDBC Programming Concepts (Statement, PreparedStatement, CallableStatement,


Resultset)
5. Introduction to Servlet
6. Session Tracking in Servlet and Filter
7. Introduction to JSP
8. JSTL and JSP database connection
9. Introduction to JSF
10. Introduction to Hibernate. Introduction to Spring
EXPERIMENT NO: 1 DATE: / /

TITLE: Introduction networking in Java.

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of Networking in java.
 Create simple programs using URL Class,URLConnection Class ,
InetAddress Class.

THEORY:

What is URL : URL is the acronym for Uniform Resource Locator. It is a reference (an
address) to a resource on the Internet. You provide URLs to your favorite Web
browser so that it can locate files on the Internet in the same way that you provide
addresses on letters so that the post office can locate your correspondents.

Java programs that interact with the Internet also may use URLs to find the resources on
the Internet they wish to access. Java programs can use a class called URL in the
java.net package to represent a URL address.The URL class provides several methods
that let you query URL objects. You can get the protocol, authority, host name, port
number, path, query, filename, and reference from a URL using these accessor
methods:The URL class contains many methods for accessing the various parts of the
URL being represented. Some of the methods in the URL class include the following −

Import java.net.*;
import java.io.*;

public class ParseURL {


public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial/index.html?
name=networkin#DOWNLOADING );
System.out.println("protocol = " aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}

Here's the output displayed by the


program:
protocol = http
authority = example.com:80
host = example.com
port = 80
path=/docs/books/tutorial/inde.html
query = name=networking
filename=/docs/books/tutorial/index.html?name=networking ref = DOWNLOADING

import java.net.*;
class MyURL
{
public static void main(String args[ ]) throws Exception
{
URL obj = new URL("http://ait.com/index.html");
System.out.println("Protocol: "+ obj.getProtocol());
System.out.println("Host: "+ obj.getHost());
System.out.println("File: "+ obj.getFile());
System.out.println("Port: "+ obj.getPort());
System.out.println("Path: "+ obj.getPath());
System.out.println("External form: "+
obj.toExternalForm());
}
}
Java URLConnection class :
The Java URLConnection class represents a communication link between the URL
and the application. This class can be used to read and write data to the specified
resource referred by the URL.The URLConnection class has many methods for setting
or determining information about the connection, including the following.

Example of Java URLConnection class


import java.io.*;
import java.net.*;
public class URLConnectionExample { public static void main(String[] args){
try{
URL url=new URL("http://gtu-info.com/Syllabus");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1)
{ System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

InetAddress class

InetAddress class has no visible constructors. To create an InetAddress object, you have
to use one of the available factory methods. Factory methods are merely a convention
whereby static methods in a class return an instance of that class. This is done in lieu of
overloading a constructor with various parameter lists when having unique method
names makes the results much clearer. In the case of InetAddress, the three methods
getLocalHost(), getByName(), and getAllByName() can be used to create instances of
InetAddress.
These methods are shown here:

static InetAddress getLocalHost( ) throws UnknownHostException.


static InetAddress getByName(String hostName) throws
UnknownHostException. static InetAddress[ ] getAllByName(String
hostName) throws UnknownHostException

The getLocalHost( ) method simply returns the InetAddress object that represents the
local host. The getByName( ) method returns an InetAddress for a host name passed to
it. If these methods are unable to resolve the host name, they throw an
UnknownHostException.

On the Internet, it is common for a single name to be used to represent several machines.
In the world of web servers, this is one way to provide some degree of scaling. The
getAllByName( ) factory method returns an array of InetAddresses that represent all of
the addresses that a particular name resolves to. It will also throw an
UnknownHostException if it can't resolve the name to at least one address.

import java.io.*;
import java.net.*;

class Address
{
public static void main(String args[ ]) throws IOException
{
//accept name of website from keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a website name: ");
String site = br.readLine();
try{
//getByName() method accepts site name and returns its IPAddress
InetAddress ip = InetAddress.getByName(site);
System.out.println("The IP Address is: "+ ip);
}
catch(UnknownHostException ue)
{
System.out.println("Website not found");
}
}
}

EXERCISE:

1. Write a program to display IP address of local machine.

2. Write a program to displaying source code of a webpage by URLConnecton class


also display length of it.

3. Write a program to display the expiration date and last modified date for the following URL
http://www.star.com/news/.
REVIEW QUESTIONS:

1. What is URL?
2. Write a Components of URL?
EVALUATION:
Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date: _________________


EXPERIMENT NO: 2 DATE: / /

TITLE: Chat Application using TCP and UDP.

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of Socket class and Datagram class.
 Create simple programs using
Socket ,ServerSocketClass,DatagramPacket,DatagramSocket.

THEORY:

URLs and URLConnections provide a relatively high-level mechanism for accessing


resources on the Internet. Sometimes your programs require lower-level network
communication, for example, when you want to write a client-server application.

In client-server applications, the server provides some service, such as processing


database queries or sending out current stock prices. The client uses the service provided
by the server, either displaying database query results to the user or making stock
purchase recommendations to an investor. The communication that occurs between the
client and the server must be reliable. That is, no data can be dropped and it must arrive
on the client side in the same order in which the server sent it.

TCP provides a reliable, point-to-point communication channel that client-server


applications on the Internet use to communicate with each other. To communicate over
TCP, a client program and a server program establish a connection to one another. Each
program binds a socket to its end of the connection. To communicate, the client and the
server each reads from and writes to the socket bound to the connection.
What is Socket and ServerSocket:

Normally, a server runs on a specific computer and has a socket that is bound to a
specific port number. The server just waits, listening to the socket for a client to make a
connection request.
On the client-side: The client knows the hostname of the machine on which the server is
running and the port number on which the server is listening. To make a connection
request, the client tries to rendezvous with the server on the server's machine and port.
The client also needs to identify itself to the server so it binds to a local port number that
it will use during this connection. This is usually assigned by the system.

If everything goes well, the server accepts the connection. Upon acceptance, the server
gets a new socket bound to the same local port and also has its remote endpoint set to
the address and port of the client. It needs a new socket so that it can continue to listen
to the original socket for connection requests while tending to the needs of the
connected client.

On the client side, if the connection is accepted, asocket is successfully created and the client
can use the socket to communicate with the server. The client and server can now communicate
by writing to or reading from their sockets.

Client Server Application using Socket


import java.io.*;
import java.net.*;
class Client2
{
public static void main(String args[ ]) throws Exception
{
//Create client socket
Socket s = new Socket("localhost", 888);
//to send data to the server
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//to read data coming from the server
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//to read data from the key board
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String str,str1;
//repeat as long as exit is not typed at client while(!(str =
kb.readLine()).equals("exit"))
{
dos.writeBytes(str+"\n");
//send to server str1 = br.readLine(); //receive from server System.out.println(str1);
}
//close connection.dos.close();
br.close();
kb.close();
s.close();
}
}

import java.io.*;
import java.net.*;
class Server2
{
public static void main(String args[ ]) throws Exception
{
//Create server socket
ServerSocket ss = new ServerSocket(888);
//connect it to client socket Socket s = ss.accept();
System.out.println("Connection established");
//to send data to the client
PrintStream ps = new PrintStream(s.getOutputStream());
//to read data coming from the client
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
//to read data from the key board
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
while(true) //server executes continuously
{
String str,str1;
//repeat as long as client does not send null string while((str = br.readLine()) !=
null) //read from client
{
System.out.println(str); str1 = kb.readLine();
ps.println(str1); //send to client
}
//close connection ps.close();
br.close();
kb.close();
ss.close();
s.close();
System.exit(0); //terminate application
} //end of while
}
}

What is DatagramPacket and DatagramSocket:

Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.Java DatagramSocket class represents a connection-less socket for
sending and receiving datagram packets.A datagram is basically an information but
there is no guarantee of its content, arrival or arrival time.Commonly used Constructors
of DatagramSocket class.

DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it


with the available Port Number on the localhost machine.

DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and


binds it with the given Port Number.
DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.

Java DatagramPacket : is a message that can be sent or received. If you send multiple
packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class

DatagramPacket(byte[] barr, int length): it creates a datagram packet. This


constructor is used to receive the packets.

DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a


datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket


//DSender.java
import java.net.*;

public class DSender{


public static void main(String[] args) throws Exception
{ DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

EXERCISE:

1. Write a TCP or UDP client and server program to do the following:

client> java client localhost/IP Port <enter>

Enter text: Welcome to Gujarat Technological UNIVERSITY

<enter> Response from server: Welcome

client> exit

2. Write a client-server program using TCP or UDP where the client sends 10 numbers and
server responds with the numbers in sorted order.
3. Write a UDP Client-Server program in which the Client sends any string and Server
responds with Reverse string.
4. Write a TCP Client-Server program to get the Date & Time details from Server on the Client request.

5. Write a client server program using TCP where client sends a string and server checks
whether that string is palindrome or not and responds with appropriate message.
6. Write a client-server program using UDP socket. Client send list of N numbers to
server and server respond the sum of N numbers.
7. Write a client-server program using UDP socket. Client sends the list of N strings
and server responds the concatenation of those strings.
REVIEW QUESTIONS:

1. How to perform connection-oriented Socket Programming in networking ?


2. How to perform connection-less socket programming in networking ?
3. How to get the IP address of any host name e.g. www.google.com ?
EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date: ________________


EXPERIMENT NO: 3 DATE: / /

TITLE: JDBC Programming Concepts.

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of JDBC Driver Types of Different Classes to
connect to database and How to get det data from database and
CURD Operation.
 Create simple programs using Statement
class,PreparedStatement class,CallableStatement class
, ResultSet class,ResultSetMetaData,
THEORY:

JDBC is Java application programming interface that allows the Java programmers to
access database management system from Java code. It was developed by JavaSoft, a
subsidiary of Sun Microsystems.

Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the
java programs to execute SQL statements. It is an application programming interface that
defines how a java programmer can access
the database in tabular format from Java code using a set of standard interfaces and
classes written in the Java programming language.

JDBC has been developed under the Java Community Process that allows multiple
implementations to exist and be used by the same application. JDBC provides methods
for querying and updating the data in Relational Database Management system such as
SQL, Oracle etc. The primary function of the JDBC API is to provide a means for the
developer to issue SQL statements and process the results in a consistent, database-
independent manner. JDBC provides rich, object-oriented access to databases by
defining classes and interfaces that represent objects such as:
1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Binary Large Objects (BLOBs)
7. Character Large Objects (CLOBs)
8. Callable statements
9. Database drivers
10. Driver manager
Processing SQL Statements with JDBC
In general, to process any SQL statement with JDBC, you follow these steps:
1. Establishing a connection.
2. Create a statement.
3. Execute the query.
4. Process the ResultSet object.
5. Close the connection.

Statement interface

The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object
of ResultSet
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into employee values(101,'RAM',20000)");


//int result=stmt.executeUpdate("update employee set name='Vimal',salary=10000 where id=102");
int result=stmt.executeUpdate("delete from employee where id=101");
System.out.println(result+" records affected"); con.close();
}}

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.

import java.sql.*; class FetchRecord{


public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UP
DATA BLE);
ResultSet rs=stmt.executeQuery("select * from employee");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

import java.sql.*;
class MysqlCon{
public static void main(String args[]){ try{ Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password Statement
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); con.close();
}catch(Exception e){ System.out.println(e);}
}
}

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:


create table emp(id number(10),name varchar2(50)); import java.sql.*;
class InsertPrepared{
public static void main(String args[]){ try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ora
cle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e)
{ System.out.println(e);}
}
}

Java ResultSetMetaData Interface

The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides methods to
get metadata from the ResultSet object.

import java.sql.*;
class Rsmd{
public static void main(String args[])
{ try{
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and functions. We can
have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.Suppose you need the
get the age of the employee based on the date of birth, you may create a function that
receives date as the input and returns age of the employee as the output.

Full example to call the stored procedure using JDBC


To call the stored procedure, you need to create it in the database. Here, we are
assuming that stored procedure looks like this
------------------------------------------------------------------------------------------------------------
> create or replace procedure "INSERTR" (id IN NUMBER,
name IN VARCHAR2)
is begin
insert into user420 values(id,name);
end;

> create table user420(id number(10), name varchar2(200));


------------------------------------------------------------------------------------------------------------
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();
System.out.println("success");
}
}

EXERCISE:
1. Write a program to insert, update, delete and print first five topper student from
student records in database using prepared statement.
2. Write a program to insert, update, delete and print record for employee having salary >
20000 from Employee table in database using statement interface.
REVIEW QUESTIONS:
1. How to connect Java application with Mysql database using JDBC?
2. What is the difference between Statement and PreparedStatement interface?
3. What is the role of Driver Manager?
EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date: _____________________


EXPERIMENT NO: 4 DATE: / /

TITLE: Introduction to Servlet .

OBJECTIVES: On completion of this experiment student will able to…


know the concept of Servlet class.
Create simple programs using HTTP methods,ServletContext and ServletConfig
interface,Request Dispacher interface.

THEORY:

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side
programming language.

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.The javax.servlet package contains many interfaces and classes that are used
by the servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for
http requests only.Let's see what are the interfaces of javax.servlet package.

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext

import javax.servlet.*;

public class First implements Servlet{

ServletConfig config=null;
public void init(ServletConfig config)
{ this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy()
{System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig()
{return config;}
public String getServletInfo()
{return "copyright 2007-1010";}

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:


1. public void service (ServletRequest req,ServletResponse res) dispatches the
request to the protected service method by converting the request and response
object into http type.
2. protected void service (HttpServletRequest req, HttpServletResponse res)
receives the request from the service method, and dispatches the request to the
doXXX() method depending on the incoming http request type.
3. protected void doGet (HttpServletRequest req, HttpServletResponse res) handles
the GET request. It is invoked by the web container.
4. protected void doPost (HttpServletRequest req, HttpServletResponse res)
handles the POST request. It is invoked by the web container.
5. protected void doHead (HttpServletRequest req, HttpServletResponse res)
handles the HEAD request. It is invoked by the web container.
6. protected void doOptions (HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
7. protected void doPut (HttpServletRequest req, HttpServletResponse res) handles
the PUT request. It is invoked by the web container.
8. protected void doTrace (HttpServletRequest req, HttpServletResponse res)
handles the TRACE request. It is invoked by the web container.
9. protected void doDelete (HttpServletRequest req, HttpServletResponse res)
handles the DELETE request. It is invoked by the web container.
10. protected long getLastModified (HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of
the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

// Import required java libraries


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

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Set response content type response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}}
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class></servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to include
the content of another resource also. It is one of the way of servlet collaboration.There
are two methods defined in the RequestDispatcher interface.
index.html
<form action="servlet1"
method="post">Name:<input type="text"
name="userName"/><br/>

Password:<input type="password" name="userPass"/><br/>


<input type="submit" value="login"/>
</form>

Login.java

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

public class Login extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
String p=request.getParameter("userPass");

if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else
{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}

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

public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{

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

String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}

web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

SendRedirect in servlet

The sendRedirect() method of HttpServletResponse interface can be used to redirect


response to another resource, it may be servlet, jsp or html file. It accepts relative as
well as absolute URL. It works at client side because it uses the url bar of the browser to
make another request. So, it can work inside and outside the server.

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

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
response.sendRedirect("http://www.google.com");
pw.close();
}}

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>

import java.io.IOException;
import javax.servlet.ServletException; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySearcher extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}

EXERCISE:
1. Design a form to input details of an employee and submit the data to a servlet. Write
code for servlet that will save the entered details as a new record in database table
Employee with fields (EmpId, EName,Email, Age).
2.Write a servlet RegistrationServlet to get the values from registration.html html
page and display the contents. Write the web.xml file.
3. Write a program to show use of ServletConfig and ServletContext.

4. Write a Login servlet. Take input username and password from html file login.html and
authenticate the user. Write the web.xml.

REVIEW QUESTIONS:

1. What is the web application


2. what is the difference between Get and Post request ?
3. How to run servlet in Netbeans IDE ?

EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date: _____________


EXPERIMENT NO: 5 DATE: / /

TITLE: Session Tracking in Servlet and Filter.

OBJECTIVES: On completion of this experiment student will able to


 Know the concept of Session Tracking and Filter Class.
 Create simple programs using Cookies, UrlRewriting, Hidden form
fields, HttpSession .

THEORY:

Session simply means a particular interval of time.


Session Tracking is a way to maintain state (data) of a user. It is also known as session
management in servlet. Http protocol is a stateless so we need to maintain state using
session tracking techniques. Each time user requests to the server, server treats the
request as the new request. So we need to maintain the state of a user to recognize to
particular user. HTTP is stateless that means each request is considered as the new
request. It is shown in the figure given below:

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet : A cookie is a small piece of information that is persisted between


the multiple client requests. 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.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

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

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response){ try{

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

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);


//creating cookie object
response.addCookie(ck);
//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}
catch(Exception e)
{System.out.println(e);}
}
}

SecondServlet.java

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

public class SecondServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}
catch(Exception e)
{System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

Servlet Filter

A filter is an object that is invoked at the preprocessing and postprocessing of a request.


It is mainly used to perform filtering tasks such as conversion, logging, compression,
encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove
the entry of filter from the web.xml file, filter will be removed automatically and we
don't need to change the servlet.
So maintenance cost will be less
Usage of Filter

● recording all incoming requests


● logs the IP addresses of the computers from which the requests originate
● conversion
● data compression
● encryption and decryption
● input validation etc.

Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance

index.html
1. <a href="servlet1">click here</a>

MyFilter.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{


public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws
IOException, ServletException {

PrintWriter out=resp.getWriter(); out.print("filter is invoked before");

chain.doFilter(req, resp);//sends request to next resource


out.print("filter is invoked after");
}
public void destroy() {}
}
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

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

out.print("<br>welcome to servlet<br>");
}
}

web.xml
For defining the filter, filter element of web-app must be defined just like servlet.

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>

</web-app>
EXERCISE:
1. Create form and perform state management using Cookies, HttpSession and URL
Rewriting.
REVIEW QUESTIONS:

1. What is the difference between ServletConfig and ServletContext interface?


2. What information is received by the web server if we request for a servlet ?

EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date: __________________


EXPERIMENT NO: 6 DATE: / /

TITLE: Introduction to JSP

OBJECTIVES: On completion of this experiment student will able to…


 Know the concept of JSP.
 Create simple programs using JSP Directives, JSP Action, JSP
Implicit Objects JSP Form Processing, JSP Session and Cookies
Handling, JSP Session Tracking

THEORY:

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.

The Lifecycle of a JSP Page


1) request index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>

2) response
Welcome1.jsp
<%
response.sendRedirect("http://www.google.com");
%>
3) Config:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
4) Application index.html
<form>
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

web.xml file

<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
5) Session
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>

second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>

6) pageContext implicit object

In JSP, pageContext is an implicit object of type PageContext class.The pageContext


object can be used to set,get or remove attribute from one of the following scopes:
● page
● request
● session
● application
In JSP, page scope is the default scope.
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user", name, PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>

second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</htm

JSP directives

The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.

There are three types of directives:

1. page directive
2. include directive
3. taglib directive
1) Page Directive attributes

 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage

Import
<html>
<body>
<%@ page
import="java.util.Date" %> Today
is: <%= new Date() %>
</body></htm> contentType
<html><body>
<%@ page
contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body></html>

Jsp Include Directive


<html><body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body></html

JSP Taglib directive


<html><body>
<%@ taglib uri="http://www.google.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body></html>

1) index.js

<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp

<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

2) jsp:include
File: index.jsp

<h2>this is index page</h2>


<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
EXERCISE:
1. Write small web application which takes marks of three subject and pass to servlet. Servlet
forward to model class having method getClass() and getPercentage(). Display class and
percentage in .jsp page
2. Write a servlet that redirect requests alternatively to JSP Pages named Odd and Even

3. Develop JSP page to display student information with subjects for particular semester from
database

4. Write a java bean named “student” having roll no and name having getter & setter methods.
Write a JSP page to set the roll number and name for a student object and then print them by
reading from object.
5.Write a student bean class with property student_name, enrollment_no, address and cpi.
Write jsp page to set and display all property.
REVIEW QUESTIONS:
1. How to run a simple JSP page?
2. What are the lifecycle stages of JSP page?
3. Name the scripting elements.

EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date:


EXPERIMENT NO: 7 DATE: / /

TITLE: JSTL and JSP database connection.

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of JSTL core,function,formatting,xml,sql tags
and JSP database CURD operations.

THEORY:
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.

Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
Ex:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="Income" scope="session" value="${4000*4}"/>
<c:out value="${Income}"/>
</body>
</html
Ex:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="income" scope="session" value="${4000*4}"/>
<p>Your income is : <c:out value="${income}"/></p>
<c:choose>
<c:when test="${income <= 1000}">
Income is not good.
</c:when>
<c:when test="${income > 10000}">
Income is very good.
</c:when>
<c:otherwise>
Income is undetermined...
</c:otherwise>
</c:choose>
</body>
</html>

JSTL Function Tags

JSTL Function Tags List

JSTL Functions Description


fn:contains() It is used to test if an input string containing the specified substring
in a program
fn:containsIgnoreCase() It is used to test if an input string contains the specified
substring as a case insensitive way.
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as XML markup.
fn:indexOf() It returns an index within a string of first occurrence of a specified
substring.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a
particular string value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase() It converts all the characters of a string to lower case.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given start and end
position.
fn:substringAfter() It returns the subset of string after a specific substring.
fn:substringBefore() It returns the subset of string before a specific substring.
fn:length() It returns the number of characters inside a string, or the number of
items in a collection.
fn:replace() It replaces all the occurrence of a string with another string sequence

Ex:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Using JSTL Function </title>
</head>
<body>
<c:set var="site" value="javatpoint.com"/>
<c:set var="author" value="Sonoo Jaiswal"/>
Hi, This is ${fn:toUpperCase(site)} developed by ${fn:toUpperCase(author)}.
</body>
</html>

JSTL formatting tags


Formatting Tags Description
fmt:parseNumber It is used to Parses the string representation of a currency, percentage or
number.
fmt:timeZone It specifies a parsing action nested in its body or the time
zone for any time formatting.
fmt:formatNumber It is used to format the numerical value with specific format or
precision.
fmt:parseDate It parses the string representation of a time and date.
fmt:bundle It is used for creating the ResourceBundle objects which will be used by
their tag body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration
variable or the named scoped variable.
fmt:message It displays an internationalized message.
fmt:formatDate It formats the time and/or date using the supplied

pattern and styles. Ex:


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<head>
<title>fmt:formatNumber Tag</title>
</head>
<body>
<h3>Formatting of Number:</h3>
<c:set var="Amount" value="9850.14115" />
<p> Formatted Number-1:
<fmt:formatNumber value="${Amount}" type="currency" /></p>
<p>Formatted Number-2:
<fmt:formatNumber type="number" groupingUsed="true" value="${Amount}" /></p>
<p>Formatted Number-3:
<fmt:formatNumber type="number" maxIntegerDigits="3" value="${Amount}" /></p>
<p>Formatted Number-4:
<fmt:formatNumber type="number" maxFractionDigits="6" value="${Amount}" /></p>
<p>Formatted Number-5:
<fmt:formatNumber type="percent" maxIntegerDigits="4" value="${Amount}" /></p>
<p>Formatted Number-6:
<fmt:formatNumber type="number" pattern="###.###$" value="${Amount}" /></p>
</body>
</html>

JSTL

XML tags

JSTL XML tags List


XML Tags Descriptions
x:out Similar to <%= ... > tag, but for XPath expressions.
x:parse It is used for parse the XML data specified either in the tag
body or an attribute.
x:set It is used to sets a variable to the value of an XPath expression.
x:choose It is a conditional tag that establish a context for mutually exclusive
conditional operations.
x:when It is a subtag of that will include its body if the condition evaluated be
'true'.
x:otherwise It is subtag of that follows tags and runs only if all the prior conditions
evaluated be 'false'.
x:if It is used for evaluating the test XPath expression and if it is true, it will
processes its body content.
x:transform It is used along with the transform tag for setting the parameter in the
XSLT style sheet. Ex:
x:transform It is used along with the transform tag for setting the parameter in the
XSLT style sheet. Ex:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>x:choose Tag</title>
</head>
<body>
<h3>Books Information:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Three mistakes of my life</name>
<author>Chetan Bhagat</author>
<price>200</price>
</book>
<book>
<name>Tomorrow land</name>
<author>Brad Bird</author>
<price>2000</price>
</book>
</books>
</c:set>

<x:parse xml="${xmltext}" var="output"/>


<x:choose>
<x:when select="$output//book/author = 'Chetan bhagat'">
Book is written by Chetan bhagat
</x:when>
<x:when select="$output//book/author = 'Brad Bird'">
Book is written by Brad Bird
</x:when>
<x:otherwise>
The author is unknown...
</x:otherwise>
</x:choose>
</body>
</html> JSTL SQL
Tags

JSTL SQL Tags List


SQL Tags Descriptions
sql:setDataSource It is used for creating a simple data source suitable only for prototyping.
sql:query It is used for executing the SQL query defined in its sql
attribute or the body.
sql:update It is used for executing the SQL update defined in its sql attribute or in
the tag body.
sql:param It is used for sets the parameter in an SQL statement to the specified
value.
sql:dateParam It is used for sets the parameter in an SQL statement to a specified
java.util.Date value.
sql:transaction It is used to provide the nested database action with a common
connection.

EXERCISE:
1. Write a JSP program using JSTL SQL taglib to display student details in tabular form by
iterating through the database table student

2. Writea login.jsp page to get the login information from user and authenticate user
with the database with JSTL SQL tags.
REVIEW QUESTIONS:
1. What is JSTL?
2. Write JSTL SQL tags with description.
EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date:


EXPERIMENT NO: 8 DATE: / /

TITLE: Introduction to JSF

OBJECTIVES: On completion of this experiment student will able to…


 Know the concept of JSF.

THEORY:
It is a server side component based user interface framework. It is used to develop web
applications. It provides a well-defined programming model and consists of rich API
and tag libraries. The latest version JSF 2 uses Facelets as its default templating system.
It is written in Java.

The JSF API provides components (inputText, commandButton etc) and helps to
manage their states. It also provides server-side validation, data conversion, defining
page navigation, provides extensibility, supports for internationalization, accessibility
etc.

The JSF Tag libraries are used to add components on the web pages and connect
components with objects on the server. It also contains tag handlers that implements the
component tag.With the help of these features and tools, you can easily and effortlessly
create server-side user interface.
JSF UI Component Model
JSF provides the developers with the capability to create Web application from
collections of UI components that can render themselves in different ways for multiple
client types (for example - HTMLbrowser, wireless, or WAP device).
JSF provides −Core library
A set of base UI components - standard HTML input elements
Extension of the base UI components to create additional UI component libraries or to
extend existingcomponents
Multiple rendering capabilities that enable JSF UI components to render themselves
differentlydepending on the client types .
JSF Architecture

JSF application is similar to any other Java technology-based web application; it runs in
a Java servletcontainer, and contains −

JavaBeans components as models containing application-specific functionality and data


A custom tag library for representing event handlers and validators
A custom tag library for rendering UI components
UI components represented as stateful objects on the serverServer-side helper classes
Validators, event handlers, and navigation handlers
Application configuration resource file for configuring application resources

There are controllers which can be used to perform user actions. UI can be created by web page authors
and the business logic can be utilized by managed beans.

JSF provides several mechanisms for rendering an individual component. It is upto the web page
designer to pick the desired representation, and the application developer doesn't need to know which
mechanism was used to render a JSF UI component.

JSF application life cycle consists of six phases which are as follows

Restore view phase


Apply request values phase; process events
Process validations phase; process events
Update model values phase; process events
Invoke application phase; process events
Render response phase
The six phases show the order in which JSF processes a form. The list shows the
phases intheir likely order of execution with event processing at each phase.

Phase 1: Restore view


JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives
a request.

During this phase, JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance. The FacesContext instance
will now contain all the information required to process a request.

Phase 2: Apply request values


After the component tree is created/restored, each component in the component tree uses
the decode method to extract its new value from the request parameters. Component stores
this value. If the conversion fails, an error message is generated and queued on
FacesContext. This message will be displayed during the render response phase, along
with any validation errors.

If any decode methods event listeners called renderResponse on the current FacesContext
instance, the JSF moves to the render response phase.

Phase 3: Process validation


During this phase, JSF processes all validators registered on the component tree. It
examines the component attribute rules for the validation and compares these rules to the
local value stored for thecomponent.

If the local value is invalid, JSF adds an error message to the FacesContext instance, and the
life cycle advances to the render response phase and displays the same page again with the
error message.

Phase 4: Update model values


After the JSF checks that the data is valid, it walks over the component tree and sets the
corresponding server-side object properties to the components' local values. JSF will
update the bean properties corresponding to the input component's value attribute.

If any updateModels methods called renderResponse on the current FacesContext instance,


JSF moves to the render response phase.

Phase 5: Invoke application


During this phase, JSF handles any application-level events, such as submitting a
form/linking to another page.

Phase 6: Render response


During this phase, JSF asks container/application server to render the page if the
application is using JSP pages. For initial request, the components represented on the page
will be added to the component tree as JSP container executes the page. If this is not an
initial request, the component tree is already built so components need not be added again.
In either case, the components will render themselves as the JSP container/Application
server traverses the tags in the page.

After the content of the view is rendered, the response state is saved so that subsequent
requests can access it and it is available to the restore view phase.
Advantages:
 It supports code reusabilty through templating and composite components.
 It provides functional extensibility of components and other server-side objects through
customization.
 Faster compilation time.
 It validates expression language at compile-time.
 High-performance rendering.

EXERCISES:
1. Create a small application to demonstrate the use of Java Server Faces.

REVIEW QUESTIONS:

1. Explain what is JSF or Java Server Faces?


2. Explain what is the JSF architecture?
3. Explain the life cycle of JSF?

EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date: __________________


EXPERIMENT NO: 9 DATE: / /

TITLE: Introduction to Hibernate.

OBJECTIVES: On completion of this experiment student will able to…


 Know the concept of Hibernate.
THEORY:
Hibernate is a Java framework that simplifies the development of Java application to interact with
the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate
implements the specifications of JPA (Java Persistence API) for data persistence.
A major portion of the development of an enterprise application involves the creation and
maintenance of the persistence layer used to store and retrieve objects from the database of choice.
Many organizations resort to creating homegrown, often buggy, persistence layers. If changes are
made to the underlying database schema, it can be expensive to propagate those changes to the
rest of the application. Hibernate steps in to fill this gap, providing an easy-to- use and powerful
object-relational persistence framework for Java applications.

Hibernate provides support for collections and object relations, as well as composite types. In
addition to persisting objects, Hibernate provides a rich query language to retrieve objects from
the database, as well as an efficient caching layer and Java Management Extensions (JMX)
support. User-defined data types and dynamic beans are also supported.

Hibernate is released under the Lesser GNU Public License, which is sufficient for use in
commercial as well as open source applications. It supports numerous databases, including Oracle
and DB2, as well as popular open source databases such as PostgreSQL and MySQL. An active
user community helps to provide support and tools to extend Hibernate and make using it easier.

How Hibernate Works?

Rather than utilize bytecode processing or code generation, Hibernate uses runtime reflection to
determine the persistent properties of a class.The objects to be persisted are defined in a mapping
document, which serves to describe the persistent fields and associations, as well as any subclasses
or proxies of the persistent object. The mapping documents arecompiled at application startup
time and provide the framework with necessary information for a class. Additionally, they are
used in support operations, such as generating the database schema or creating stub Java source
files.

A SessionFactory is created from the compiled collection of mapping documents.


The SessionFactory provides the mechanism for managing persistent classes, the Session
interface. The Session class provides the interface between the persistent data store and the
application. The Sessioninterface wraps a JDBC connection, which can be user-managed or
controlled by Hibernate, and is only intended to be used by a single application thread, then closed
and discarded.

The Mapping Documents

Our example utilizes two trivial classes, Teamand Player. The mappings for these classes are
shown below.
<hibernate-mapping>
<class name="example.Team" table="teams">
<id name="id" column="team_id" type="long" unsaved-value="null">
<generator class="hilo"/>
</id>
<property name="name" column="team_name"
type="string" length="15" not-null="true"/>
<property name="city" column="city" type="string"
length="15" not-null="true"/>
<set name="players" cascade=”all" inverse="true" lazy="true">
<key column="team_id"/>
<one-to-many class="example.Player"/>
</set>
</class>
</hibernate-mapping>
example.Team mapping document.

<hibernate-mapping>
<class name="example.Player" table="players">
<id name="id" column="player_id" type="long" unsaved-value="null">
<generator class="hilo"/>
</id>
<property name="firstName" column="first_name" type="string"
length="12" not-null="true"/>
<property name="lastName" column="last_name" type="string"
length="15" not-null="true"/>
<property name="draftDate" column="draft_date" type="date"/>
<property name="annualSalary" column="salary" type="float"/>
<property name="jerseyNumber"
column="jersey_number" type="integer"
length="2" not-null="true"/>
<many-to-one name="team" class="example.Team" column="team_id"/>
</class>
</hibernate-mapping>
example.Player mapping document

The mapping documents are reasonably clear, but certain areas warrant explanation. The id
element block describes the primary key used by the persistent class. The attributes of the id
element are:
 name: The property name used by the
persistentclass. column: The column used to
store the primary keyvalue.
 type: The Java data type used. In this case, we’re going to use longs.
 unsaved-value: This is the value used to determine if a class has been made
persistent, i.e., stored to the database. If the value of the id attribute is null,
Hibernate knows that this object has not been persisted. This is important when
calling the saveOrUpdate()method, discussed later.
The generator element describes the method used to generate primary keys. I’ve chosen to
use the hilo generator for purposes of illustration. The hilo generator will use a supporting
table to create the key values. If this method doesn’t appeal to you, don’t worry. In
Hibernate 2.0, ten primary key generation methods are available and it’s possible to
create your ownmechanism, including composite primary keys.

The property elements define standard Java attributes and how they are mapped to columns in
the schema. Attributes are available to specify column length, specific SQL types, and whether
or not to accept null values. The property element supports the column child element to specify
additional properties, such as the index name on a column or a specific column type.

Our Teamclass has an additional element block for the collection of Players that belong to a
Team
:
<set name="players" cascade=”all” inverse=”true” lazy=”true”>
<key column="team_id"/>
<one-to-many class="example.Player"/>
</set>
This defines a set of Players that will be mapped to the Teamusing the bi-directional mapping
defined in the Player class, which Hibernate will create when the schema is generated.
The keyelement is used to distinguish an instance of the collection using a foreign key to the
owning entity. The one-to-many element specifies the collected class and the column used to
map to the entity.

Two attributes in the set element are of interest: lazy and inverse. Marking a collection as
lazy=”true” means that the collection will not be automatically populated when the object
containing the collection is retrieved from the database. For example, if we retrieve a Teamfrom
the database, the set of Players will not be populated until the application accesses it. Lazy
initialization of collections will be explained in more detail in the Performance Considerations
section.

The inverseattribute allows this set to be bi-directional, meaning that we can determine the
Team that a Playerbelongs to with the following entry from the Playermapping document:

Hibernate Properties
The properties that Hibernate uses to connect to the database and generate the schema are stored
in a file called hibernate.properties. For our purposes, this file only has five properties, but
many more are available:

hibernate.connection.username=ralph
hibernate.connection.password=nader
hibernate.connection.url=jdbc:postgresql://localhost/example
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.dialect=net.sf.hibernate.dialect.PostgreSQLDialect
example hibernate.properties
The first four property values are familiar to any developer that has worked with JDBC. The last
property, hibernate.dialect, defines the SQL dialect used when converting the Hibernate Query
Language (HQL) into SQL, as well as when generating the database schema for initial use. If we
chose to use Oracle instead of PostgreSQL in the future, we’d simply change the dialect used and
update the connection parameters as necessary. The HQL statements would largely stay the same
except for features unique to a given database, such as the lack of nested select statements in
MySQL.

The Schema

Mapping files in hand, it’s time to generate the database schema. Hibernate ships with the
SchemaExport utility that will create the schema necessary for the mapping documents. This
utility may be run from the command line or from an Ant build script to connect to the database
and create the schema, or to export the schema to a file.

java -cp classpath \


net.sf.hibernate.tool.hbm2ddl.SchemaExport options mapping_files
SchemaExport usage

This is what our schema looks like:

generated databaseschema

The hibernate_unique_key table is used to store the id value used for the hilo generator type.

The Source Files

Rather than create the persistent classes by hand, I’ve chosen to use the CodeGenerator that ships
with the Hibernate Extensions package. The CodeGenerator will create stub files based on the
mapping documents described above, which are suitable for our needs. (The code bundle
supporting this article can be found in the Resources section.) Using the CodeGeneratoris similar
to the SchemaExportutility:

java -cp classpath \


net.sf.hibernate.tool.hbm2java.CodeGenerator options mapping_files

The generated classes have the following structure (constructors removed from diagram for
brevity):

diagram of example classes generated byHibernate

Creating the SessionFactory

The SessionFactory stores the compiled mapping documents specified when the factory is created.
Configuring the SessionFactory is fairly straightforward. All of the mappings are added to an
instance of net.sf.hibernate.cfg.Configuration, which is then used to create the SessionFactory
instance.
Configuration cfg = new Configuration()
.addClass(example.Player.class)
.addClass(example.Team.class);
SessionFactory factory = cfg.buildSessionFactory();

Figure 10 – Configuring and creating a SessionFactory


The Configuration class is only needed for the creation of the SessionFactory and can be discarded
after the factory is built. Instances of Session are obtained by calling
SessionFactory.openSession(). The logical lifecycle of a Session instance is the span of a database
transaction.

The SessionFactory can also be configured using an XML mapping file, placed in the root of your
classpath. The obvious advantage to this approach is that your configuration isn’t
hardcoded in the application.
Creating and Updating Persistent Classes

As far as Hibernate is concerned, classes are either transient or persistent. Transient classes are
instances that have not been saved to the database. To make a transient instance persistent,
simply save it using the Sessionclass:

Player player = new Player();


// … populate player object
Session session = SessionFactory.openSession();
session.saveOrUpdate(player);
saving persistentobjects

The saveOrUpdate(Object) call will save the object if the id property is null, issuing a SQL
INSERT to the database. This refers to the unsaved-value attribute that we defined in the Player
mapping document. If the id is not null, the saveOrUpdate(Object) call would issue an update, and
a SQL UPDATE would be issued to the database. (Please refer to the sidebar Unsaved-Value
Strategies for more information on this topic.)
To create and save a Teamwith assigned Players, follow the same pattern of creating the object
and saving it with a Sessioninstance:

Team team = new Team();


team.setCity(“Detroit”);
team.setName(“Pistons”);

// add a player to the team. Player


player = new Player();
player.setFirstName(“Chauncey”);
player.setLastName(“Billups”);
player.setJerseyNumber(1);
player.setAnnualSalary(4000000f);
Set players = new HashSet();
players.add(player);

team.setPlayers(players);
// open a session and save the team
Session session = SessionFactory.openSession();
session.saveOrUpdate(team);
EXERCISES:
1. Create a small application to demonstrate the use of Hibernate.
REVIEW QUESTIONS:
1. What are the advantages of Hibernate framework?
2. Which are the elements of Hibernate Architecture?

EVALUATION:
Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date:____________


EXPERIMENT NO: 10 DATE: / /

TITLE: Introduction to Spring

OBJECTIVES: On completion of this experiment student will able to…


 Know the concept of Spring framework.
THEORY:
Spring Framework is a Java platform that provides comprehensive infrastructure support for
developing Java applications. Spring handles the infrastructure so you can focus on your
application.

Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply
enterprise services non-invasively to POJOs. This capability applies to the Java SE
programming model and to full and partial Java EE.

Examples of how you, as an application developer, can use the Spring platform advantage:

Make a Java method execute in a database transaction without having to deal with transaction
APIs.Make a local Java method a remote procedure without having to deal with remote APIs.
Make a local Java method a management operation without having to deal with JMX APIs.
Make a local Java method a message handler without having to deal with JMS APIs.

Dependency Injection and Inversion of Control

Java applications -- a loose term that runs the gamut from constrained applets to n-tier server-
side enterprise applications -- typically consist of objects that collaborate to form the
application proper. Thus the objects in an application have dependencies on each other.

Although the Java platform provides a wealth of application development functionality, it lacks
the means to organize the basic building blocks into a coherent whole, leaving that task to
architects and developers. True, you can use design patterns such as Factory, Abstract Factory,
Builder, Decorator, and Service Locator to compose the various classes and object instances
that make up an application. However, these patterns are simply that: best practices given a
name, with a description of what the pattern does, where to apply it, the problems it addresses,
and so forth. Patterns are formalized best practices that you must implement yourself in your
application.

The Spring Framework Inversion of Control (IoC) component addresses this concern by
providing a formalized means of composing disparate components into a fully working
application ready for use. The Spring Framework codifies formalized design patterns as first-
class objects that you can integrate into your own application(s). Numerous organizations and
institutions use the Spring Framework in this manner to engineer robust, maintainable
applications.

Modules
The Spring Framework consists of features organized into about 20 modules. These modules
are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented
Programming), Instrumentation, and Test, as shown in the following diagram.
Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language modules.

The Core and Beans modules provide the fundamental parts of the framework, including the
IoC and Dependency Injection features. The BeanFactory is a sophisticated implementation of
the factory pattern. It removes the need for programmatic singletons and allows you to decouple
the configuration and specification of dependencies from your actual program logic.

The Context module builds on the solid base provided by the Core and Beans modules: it is a
means to access objects in a framework-style manner that is similar to a JNDI registry. The
Context module inherits its features from the Beans module and adds support for
internationalization (using, for example, resource bundles), event-propagation, resource-
loading, and the transparent creation of contexts by, for example, a servlet container. The
Context module also supports Java EE features such as EJB, JMX ,and basic remoting. The
ApplicationContext interface is the focal point of the Context module.

The Expression Language module provides a powerful expression language for querying and
manipulating an object graph at runtime. It is an extension of the unified expression language
(unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting
property values, property assignment, method invocation, accessing the context of arrays,
collections and indexers, logical and arithmetic operators, named variables, and retrieval of
objects by name from Spring's IoC container. It also supports list projection and selection as
well as common list aggregations.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules.

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious
JDBCcoding and parsing of database-vendor specific error codes.

The ORM module provides integration layers for popular object-relational mapping APIs,
including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all of these
O/R-mapping frameworks in combination with all of the other features Spring offers, such as
the simple declarativetransaction management feature mentioned previously.

The OXM module provides an abstraction layer that supports Object/XML mapping
implementationsfor JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service (JMS) module contains features for producing and consuming
messages.

The Transaction module supports programmatic and declarative transaction management for
classesthat implement special interfaces and for all your POJOs (plain old Java objects).

Web
The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.

Spring's Web module provides basic web-oriented integration features such as multipart file-
uploadfunctionality and the initialization of the IoC container using servlet listeners and a web-
oriented application context. It also contains the web-related parts of Spring's remoting support.

The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for


web applications. Spring's MVC framework provides a clean separation between domain model
code andweb forms, and integrates with all the other features of the Spring Framework.

The Web-Struts module contains the support classes for integrating a classic Struts web tier
within a Spring application. Note that this support is now deprecated as of Spring 3.0. Consider
migrating your application to Struts 2.0 and its Spring integration or to a Spring MVC solution.

The Web-Portlet module provides the MVC implementation to be used in a portlet environment
andmirrors the functionality of Web-Servlet module.

AOP and Instrumentation


Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming
implementation allowing you to define, for example, method-interceptors and pointcuts to
cleanly decouple code that implements functionality that should be separated. Using source-
level metadata functionality, you can also incorporate behavioral information into your code, in
a manner similar tothat of .NET attributes.

The separate Aspects module provides integration with AspectJ.


The Instrumentation module provides class instrumentation support and class loader
implementationsto be used in certain application servers.

Test
The Test module supports the testing of Spring components with JUnit or TestNG. It provides
consistent loading of Spring Application Contexts and caching of those contexts. It also
providesmock objects that you can use to test your code in isolation.

Usage scenarios
The building blocks described previously make Spring a logical choice in many scenarios, from
applets to full-fledged enterprise applications that use Spring's transaction management
functionalityand web framework integration.

Typical full-fledged Spring web application

Spring's declarative transaction management features make the web application fully
transactional, just as it would be if you used EJB container-managed transactions. All your
custom business logic can be implemented with simple POJOs and managed by Spring's IoC
container. Additional services include support for sending email and validation that is
independent of the web layer, which lets you choose where to execute validation rules. Spring's
ORM support is integrated with JPA, Hibernate, JDO and iBatis; for example, when using
Hibernate, you can continue to use your existing mapping files and standard Hibernate
SessionFactory configuration. Form controllers seamlessly integrate the web-layer
with the domain model, removing the need for ActionForms or other classes that transform
HTTPparameters to values for your domain model.

EXERCISES:
1. Create a small application to demonstrate the use of Spring.

REVIEW QUESTIONS:
1. What is Spring?
2. What are the advantage of Spring?
3. What are the modules of spring framework?
4. What id IOC and DI?

EVALUATION:

Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)

Signature with date:____________

You might also like