Lab - Manual
Lab - Manual
Lab - Manual
INDEX
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.*;
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.
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:
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:
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)
THEORY:
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.
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
}
}
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.
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
EXERCISE:
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:
Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)
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();
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
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");
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
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
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
");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
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.
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)
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.
import javax.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";}
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.
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/>
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.*;
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
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<!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:
EVALUATION:
Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)
THEORY:
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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
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.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
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:
EVALUATION:
Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)
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.
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>
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.
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>
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
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)
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>
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
XML tags
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)
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 −
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
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.
If any decode methods event listeners called renderResponse on the current FacesContext
instance, the JSF moves to the render response phase.
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.
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:
EVALUATION:
Problem
Understanding Timely
Analysis & Mock Total
Level Completion
Solution (2) (10)
(3) (2)
(3)
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.
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.
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.
generated databaseschema
The hibernate_unique_key table is used to store the id value used for the hilo generator type.
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:
The generated classes have the following structure (constructors removed from diagram for
brevity):
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();
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:
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.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)
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.
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-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.
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.
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)