Vous êtes sur la page 1sur 186

Ajt paper

solution....for gtu
student....Advance
java technology.
Monday, 18 May 2015

gtu ajt paper solution advance java paper solution


Advance Java Technology
Term: WINTER 2012 Subject code: 170703 Date: 01/01/2013
Q.1 (a) Explain the need of MVC architecture. Write swing code to
create toggle button
and checkbox and handle their click event. Differentiate between
toggle button and
checkbox. (07)
Solution:
The main aim of the MVC architecture is to separate the business
logic and application data
from the presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
1. They are resuable : When the problems recurs, there is no need to
invent a new
solution, we just have to follow the pattern and adapt it as necessary.
2. They are expressive: By using the MVC design pattern our
application becomes more
expressive.
1). Model: The model object knows about all the data that need to be
displayed. It is model who is aware about all the operations that can
be applied to transform that object. It only represents the data of an
application. The model represents enterprise data and the
business rules that govern access to and updates of this data. Model
is not aware about the presentation data and how that data will be
displayed to the browser.
2). View : The view represents the presentation of the application.
The view object refers to the model. It uses the query methods of the
model to obtain the contents and renders it. The
view is not dependent on the application logic. It remains same if
there is any modification in
the business logic. In other words, we can say that it is the
responsibility of the of the view's to
maintain the consistency in its presentation when the model
changes.
3). Controller: Whenever the user sends a request for something
then it always go through
the controller. The controller is responsible for intercepting the
requests from view and passes
it to the model for the appropriate action. After the action has been
taken on the data, the
controller is responsible for directing the appropriate view to the user.
In GUIs, the views and
the controllers often work very closely together.
:: swing code to create toggle button and checkbox
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractButton;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-1
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class ToggleButtonCheckBoxRadioButton extends JFrame {
public static void main(String[] args) {
ToggleButtonCheckBoxRadioButton that = new
ToggleButtonCheckBoxRadioButton();
that.setVisible(true);
}
public ToggleButtonCheckBoxRadioButton() {
setSize(450, 350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new TogglePanel(), BorderLayout.SOUTH);
}
}
class TogglePanel extends JPanel {
public TogglePanel() {
JToggleButton tog = new JToggleButton("Toggle");
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
AbstractButton abstractButton =
(AbstractButton)itemEvent.getSource();
Color foreground = abstractButton.getForeground();
Color background = abstractButton.getBackground();
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
abstractButton.setForeground(background);
abstractButton.setBackground(foreground);
AbstractButton src = (AbstractButton) (e.getSource());
System.out.println("Toggle: " + src.getText());
}
};
aCheckBox4.addItemListener(itemListener);
tog.addItemListener(listener);
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-2
add(tog);
JCheckBox cbox = new JCheckBox("Checkbox");
cbox.addItemListener(listener);
add(cbox);
}
}
}
:: Difference between Toggle Button and CheckBox:-
Toggle button - Indicates a state, such as Yes/No, or a mode, such
as On/Off. The button
alternates between an enabled and disabled state when it is clicked.
For example, you can
use a toggle button to switch between design mode and edit mode,
or as an alternative to a
check box.
Check box - Allows a user to select or unselect one or more values in
a group of choices.
You can select more than one check box at a time on a worksheet or
in a group box. For
example, you can use a check box to create an order form that
contains a list of available
items or in an inventory tracking application to show whether an item
has been discontinued.
(b) Explain JDBC driver types. Write a Java Bean to connect to
database and insert in
the database. Query will be passed as a message to bean.
Solution:
JDBC Driver Types:
What is JDBC Driver ?
JDBC drivers implement the defined interfaces in the JDBC API for
interacting with your
database server.
For example, using JDBC drivers enable you to open database
connections and to interact
with it by sending SQL or database commands then receiving results
with Java.
The Java.sql package that ships with JDK contains various classes
with their behaviours
defined and their actual implementaions are done in third-party
drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of
operating systems and
hardware platforms in which Java operates. Sun has divided the
implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below:
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers
installed on each client
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-3
machine. Using ODBC requires configuring on your system a Data
Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most
databases only supported
ODBC access but now this type of driver is recommended only for
experimental use or when
no other alternative is available.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example
of this kind of driver.
Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++
API calls which are unique
to the database. These drivers typically provided by the database
vendors and used in the
same manner as the JDBC-ODBC Bridge, the vendor-specific driver
must be installed on
each client machine.
If we change the Database we have to change the native API as it is
specific to a database
and they are mostly obsolete now but you may realize some speed
increase with a Type 2
driver, because it eliminates ODBC's overhead.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-4
The Oracle Call Interface (OCI) driver is an example of a Type 2
driver.
Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to accessing
databases. The JDBC clients
use standard network sockets to communicate with an middleware
application server. The
socket information is then translated by the middleware application
server into the call format
required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code
installed on the client and a
single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning
that it makes calls for
the client application. As a result, you need some knowledge of the
application server's
configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to
communicate with the database,
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-5
understanding the nuances will prove helpful.
Type 4: pure Java:
In a Type 4 driver, a pure Java-based driver that communicates
directly with vendor's
database through socket connection. This is the highest performance
driver available for the
database and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install
special software on the client
or server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the
proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
Program that Connect to the Database Using Java Bean and Insert
data into the
Database. Message for Passing Query as well.
File Name: beancode.java
import java.sql.*;
public class beancode {
private String username;
private String password;
private Connection con = null;
private ResultSet rs = null;
private PreparedStatement st = null;
String url = "jdbc:mysql://localhost:3306/";;
String db = "register";
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-6
public beancode(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url+db,"root","root");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public void setusername(String userId){
username = userId;
}
public String getusername(){
return (username);
}
public void setpassword(String pass){
password = pass;
}
public String getpassword(){
return (password);
}
public void insert(){
try{
String s1="insert into userlogin
values('"+username+"','"+password+"')";
st = con.prepareStatement(s1);
st.executeUpdate();
st.clearParameters();
st.close();
}
catch(Exception m){
}
}
}
File Name: DataBase.jsp
<%@ page language="Java" import="java.sql.*" %>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
<head>
</head>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-7
<body>
<form name="form1" action="beancode" method="POST">
UserName: <input type="text" name ="userId"> <br>
Password: <input type="password" name ="pass"> <br>
<input type = "submit" value="Submit">
<jsp:useBean id="beancode" class="beancode">
<jsp:setProperty name="beancode" property="userId"/>
<jsp:setProperty name="beancode" property="pass"/>
</jsp:useBean>
</form>
</body>
</html>
Q.2 (a) Write a TCP or UDP client and server program to do the
following:
client> java client localhost/IP Port <enter>
Enter text: This is my text to be changed by the SERVER <enter>
Response from server: revres EHT YB DEGNAHC EB OT TXET YM
SI SIHt
client> exit
TCP SERVER:
import java.io.*;
import java.net.*;
/**
*/
public class SimpleTCPServer {
public static void main(String[] args){
try{
//Create server socket listening on port 8888
ServerSocket server = new ServerSocket(8888);
while(true){
System.out.println("Waiting for client to connect...");
Socket socket = server.accept();
//Create read/write from socket
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-8
new InputStreamReader(socket.getInputStream()));
//client address
InetAddress remoteIp = socket.getInetAddress();
//Receiving from client
String msg = in.readLine();
System.out.println("Client " + remoteIp + " : " + msg);
//Sending a reversed string
msg = reverseString(msg.trim());
out.println(msg);
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
private static String reverseString(String input) {
StringBuilder buf = new StringBuilder(input);
return buf.reverse().toString();
}
}
Simple TCP CLIENT:
import java.net.*;
import java.io.*;
/**
*
*/
public class SimpleTCPClient {
public static void main(String[] args){
try{
Socket socket = new Socket("127.0.0.1", 8888);
//Define read/write from socket
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//Send hello message
String msg = "Hello";
out.println(msg);
//Receive a reversed message
msg = in.readLine();
System.out.println("Server : " + msg);
}catch(IOException ioe){
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-9
ioe.printStackTrace();
}
}
}
(b) Write RMI client/server implementation to read content of the file
on server at client.
Filename is passed by the client to server.
Interface
import java.rmi.*;
public interface StackInter extends Remote
{
byte[] st(String str)throws RemoteException;
}
Implementation
import java.rmi.*;
import java.rmi.server.*;
import java.io.*;
import java.util.*;
public class StackImpl extends UnicastRemoteObject implements
StackInter
{
public StackImpl() throws RemoteException {}
public byte[] st(String str)throws RemoteException
{
try
{
File f=new File(str);
byte b[]=new byte[(int)f.length()];
BufferedInputStream f1=
new BufferedInputStream(new FileInputStream(f));
f1.read(b,0,b.length);
f1.close();
return(b);
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-10
}
catch(Exception e) { }
}
}
Server
import java.rmi.*;
import java.net.*;
public class StackServer
{
public static void main(String arg[])
{
try
{
StackImpl im=new StackImpl();
Naming.rebind("hai",im);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Client
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class NormalClient
{ public static void main(String[] arg)
{
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-11
String IpName,FileName,Ip;
StackInter DataObject;
byte[] Content;
try { BufferedReader Buffer=new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Ip Address :");
IpName = Buffer.readLine();
System.out.println("Enter the File Name :");
FileName = Buffer.readLine();
Ip="rmi://"+IpName+"/hai";
DataObject=(StackInter)Naming.lookup(Ip);
Content = DataObject.st(FileName);
File Fn=new File(FileName);
BufferedOutputStream OutFile=new BufferedOutputStream(new
FileOutputStream(Fn.getName()));
OutFile.write(Content,0,Content.length);
OutFile.flush();
OutFile.close();
}
catch(Exception e){}
}
}
Advance Java Technology
Term: WINTER 2013 Subject code: 170703 Date: 01/01/2013
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-12
Q.3 (a) Explain need of JNDI with diagram.J2EE architecture with
diagram. 07
Solution:
Naming Service? Is a service which allows us to store and retrieve
simple objects with a
unique name. It is just like one of the storage unit.
Directory Service? Is an added service on top of naming service
which allows us to store
and retrieve objects with some directory names (i.e, maintained into
groups)
These services are implemented by different vendors where each
vendor provides their own
APIs and protocols to interact with theirs naming and directory
services.
If any java application wants to use these services, it has to plugin to
any of the vendor
provided implementation, then
● Application becomes vendor specific
● While deploying we need to know about the vendor and its service
API
● While migrating the application from one vendor to another we
need to change the
code base of the application
To avoid these problems we want a standard abstraction through
which a java application
can interact with any vendor implemented Naming and Directory
Service. To meet the above
requirement SUN has released standard API providing solution to the
above mentioned
problems. These standards have been released under JNDI (Java
Naming and Directory
Service)
JNDI is an standard abstraction which allows any java application to
interact with any vendor
implemented naming and Directory Service.
In this case if java application wants to interact with any naming
registry it just requires to
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-13
prepare a request in JNDI format using JNDI API i.e, request is
explained and submitted to
JNDI API classes where JNDI API uses the information given by the
java application and
locates the SPI implementation and initializes it.
JNDI API dispatches the request to the SPI implementation through
JNDI SPI.
SPI implementation converts the request and interact with the
respective registry to process
the request, collects the response convert it into the JNDI format and
return it.
JNDI API returns response to the java application.
::J2EE architecture with diagram:-
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-14
J2EE Architecture
J2EE Server
The J2EE server provides the following services:
Naming and Directory - allows programs to locate services and
components through the Java
Naming and Directory InterfaceTM (JNDI) API
Authentication - enforces security by requiring users to log in
HTTP - enables Web browsers to access servlets and JavaServer
PagesTM (JSP) files
EJB - allows clients to invoke methods on enterprise beans
EJB Container
Enterprise bean instances run within anEJB container. The container
is a runtime environment
that controls the enterprise beans and provides them with important
system-level services.
Since you don't have to develop these services yourself, you are free
to concentrate on the
business methods in the enterprise beans. The container provides
the following services to
enterprise beans:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-15
Transaction Management
Security
Remote Client Connectivity
Life Cycle Management
Database Connection Pooling
Transaction Management
When a client invokes a method in an enterprise bean, the container
intervenes in order to
manage the transaction. Because the container manages the
transaction, you do not have to
code transaction boundaries in the enterprise bean. The code
required to control distributed
transactions can be quite complex. Instead of writing and debugging
complex code, you
simply declare the enterprise bean's transactional properties in the
deployment descriptor file.
The container reads the file and handles the enterprise bean's
transactions for you.
Security
The container permits only authorized clients to invoke an enterprise
bean's methods. Each
client belongs to a particular role, and each role is permitted to
invoke certain methods. You
declare the roles and the methods they may invoke in the enterprise
bean's deployment
descriptor. Because of this declarative approach, you don't need to
code routines that enforce
security.
Remote Client Connectivity
The container manages the low-level communications between
clients and enterprise beans.
After an enterprise bean has been created, a client invokes methods
on it as if it were in the
same virtual machine.
Life Cycle Management
An enterprise bean passes through several states during its lifetime.
The container creates
the enterprise bean, moves it between a pool of available instances
and the active state, and
finally, removes it. Although the client calls methods to create and
remove an an enterprise
bean, the container performs these tasks behind the scenes.
Database Connection Pooling
A database connection is a costly resource. Obtaining a database
connection is timeconsuming
and the number of connnections may be limited. To alleviate these
problems, the
container manages a pool of database connections. An enterprise
bean can quickly obtain
a connection from the pool. After the bean releases the connection, it
may be re-used by
another bean.
(b) Explain Object serialization and how it can be done in java. 07
Solution:
Java provides a mechanism, called object serialization where an
object can be represented as
a sequence of bytes that includes the object's data as well as
information about the object's
type and the types of data stored in the object.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-16
After a serialized object has been written into a file, it can be read
from the file and
deserialized that is, the type information and bytes that represent the
object and its data can
be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent,
meaning an object can be
serialized on one platform and deserialized on an entirely different
platform.
Classes ObjectInputStream and ObjectOutputStream are high-level
streams that contain the
methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for
writing various data types,
but one method in particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output
stream. Similarly, the
ObjectInputStream class contains the following method for
deserializing an object:
public final Object readObject() throws IOException,
ClassNotFoundException
This method retrieves the next Object out of the stream and
deserializes it. The return value is
Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use
the Employee class that
we discussed early on in the book. Suppose that we have the
following Employee class,
which implements the Serializable interface:
public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name
+ " " + address);
}
}
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The
following SerializeDemo
program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is
created. The program
does not generate any output, but study the code and try to
determine what the program is
doing.
Note: When serializing an object to a file, the standard convention in
Java is to give the file
a .ser extension.
import java.io.*;
public class SerializeDemo
{
public static void main(String [] args)
{
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-17
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
OR
Q.3 (a) Enlist and explain the need of filters with a program. 07
Solution:
Servlet Filters are Java classes that can be used in Servlet
Programming for the following
purposes:
● To intercept requests from a client before they access a resource
at back end.
● To manipulate responses from server before they are sent back to
the client.
There are are various types of filters suggested by the specifications:
● Authentication Filters.
● Data compression Filters.
● Encryption Filters.
● Filters that trigger resource access events.
● Image Conversion Filters.
● Logging and Auditing Filters.
● MIME-TYPE Chain Filters.
● Tokenizing Filters .
● XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and
then map to either servlet
names or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an
instance of each filter
that you have declared in the deployment descriptor. The filters
execute in the order that they
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-18
are declared in the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter
interface. The
javax.servlet.Filter interface defines three methods:
S.N. Method & Description
1 public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method is called by the container each time a request/response
pair is passed
through the chain due to a client request for a resource at the end of
the chain.
2 public void init(FilterConfig filterConfig)
This method is called by the web container to indicate to a filter that it
is being placed
into service.
3 public void destroy()
This method is called by the web container to indicate to a filter that it
is being taken
out of service.
Servlet Filter Example:
Following is the Servlet Filter Example that would print the clients IP
address and current date
time. This example would give you basic understanding of Servlet
Filter, but you can write
more sophisticated filter applications using the same concept:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Implements Filter class
public class LogFilter implements Filter {
public void init(FilterConfig config)
throws ServletException{
// Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
// Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-19
// Log the IP address and current timestamp.
System.out.println("IP "+ ipAddress + ", Time "
+ new Date().toString());
// Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy( ){
/* Called before the Filter instance is removed
from service by the web container*/
}
}
(b) Explain internationalization and its use using java. 07
Solution:
Customers expect products to conform to their cultural preferences,
especially when it comes
to language and data formats. You've probably been involved in
creating applications in C,
C++, or a 4GL that accommodate those expectations, but do you
know how to write great
global applications in the Java programming language?
Creating a global application isn't particularly difficult, but it does
require you to become
familiar with the most common international problems and their
solutions. The problems
associated with creating an international application are basically the
same from one
computing environment and language to any other. Solutions are
roughly equivalent as well,
although their implementations obviously differ among the various
computing environments
and programming languages. This article gives an overview of
internationalization topics and
concepts in a Java programming environment, and covers the
following features available in
the Java Development Kit 1.1.
● Locale
● Resource bundles
● Character sets
● Layout managers
Locale
Locales are used throughout the Java class libraries to customize
how data is presented
and formatted. They affect language choice, collation, calendar
usage, date and
time formats, number and currency formats, and many other
culturally sensitive data
representations. If you intend to create international Java
applications, you'll definitely use the
java.util.Locale class. There's no getting around it; you'll use Locales
to create well-behaved,
internationalized, multilingual Java applications. So, if you haven't
had time to explore all
the JDK 1.1 international features yet, you'll get a clearer
understanding of the core of the
internationalization model, the Locale, as you read and understand
the descriptions and
examples in this article.
A Locale is a relatively simple object. It identifies a specific language
and a geographic
region. In fact, the only significant contents of a Locale object are
language and country.
Although superficially these attributes are not particularly impressive,
they represent a
very rich and interesting set of information. A Locale object
represents the language and
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-20
cultural preferences of a geographic area. Language is a fairly easy
idea to grasp; cultural
preferences may not be immediately clear. Dates, time, numbers,
and currency are all
examples of data that is formatted according to cultural expectations.
Cultural preferences
are tightly coupled to a geographic area; that's why country is an
important element of locale.
Together these two elements (language and country) provide a
precise context in which
information can be presented. Using Locale, you can present
information in the language and
form that is best understood and appreciated by the user.
Language
A Locale's language is specified by the ISO 639 standard, which
describes valid language
codes that can be used to construct a Locale object. The following
figure lists a few language
codes in the standard. Because language is so dependent on
geography, a language code
might not capture all the nuances of usage in a particular area. For
example, Canadian
French and Swiss French may use different phrases and terms to
mean different things even
though basic grammar and vocabulary are the same. For this reason,
language is only half of
a well-constructed Locale object.
Language Code Language
en English
fr French
zh Chinese
ja Japanese
Country
The Locale's country identifier is also specified by an ISO standard,
ISO 3166, which
describes valid two-letter codes for all countries. ISO 3166 defines
these codes in uppercase
letters. The following figure lists a few countries that are part of the
standard. Although the
Locale constructor allows lowercase letters, it promptly converts the
code to uppercases
to create the correct internal representation. The country code
provides more contextual
information for a locale and affects a language's usage, word
spelling, and collation rules.
Country Code Country
US United States
FR France
CA Canada
Q.4 (a) Explain Servlet life cycle & importance of context object. 07
Solution:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-21
A servlet life cycle can be defined as the entire process from its
creation till the destruction.
The following are the paths followed by a servlet
● The servlet is initialized by calling the init () method.
● The servlet calls service() method to process a client's request.
● The servlet is terminated by calling the destroy() method.
● Finally, servlet is garbage collected by the garbage collector of the
JVM.
Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when
the servlet is first created,
and not called again for each user request. So, it is used for one-time
initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL
corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is
first started.
When a user invokes a servlet, a single instance of each servlet gets
created, with each user
request resulting in a new thread that is handed off to doGet or
doPost as appropriate. The
init() method simply creates or loads some data that will be used
throughout the life of the
servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}
The service() method :
The service() method is the main method to perform the actual task.
The servlet container (i.e.
web server) calls the service() method to handle requests coming
from the client( browsers)
and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and
calls service. The service() method checks the HTTP request type
(GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method
invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing
to do with service()
method but you override either doGet() or doPost() depending on
what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in
each service request.
Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an
HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-22
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists
POST as the METHOD and
it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() method :
The destroy() method is called only once at the end of the life cycle
of a servlet. This method
gives your servlet a chance to close database connections, halt
background threads, write
cookie lists or hit counts to disk, and perform other such cleanup
activities.
After the destroy() method is called, the servlet object is marked for
garbage collection. The
destroy method definition looks like this:
public void destroy() {
// Finalization code...
}
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
● First the HTTP requests coming to the server are delegated to the
servlet container.
● The servlet container loads the servlet before invoking the service()
method.
● Then the servlet container handles multiple requests by spawning
multiple threads,
each thread executing the service() method of a single instance of
the servlet.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-23
(b) Write line(s) of code in JSP for following. 07
I. Session read and write
II. URL rewriting sending and retrieving parameter(s)
III. URL redirection
IV. Print “hello world” as output
V. Include the other JSP file statically
VI. Expression to display date as output
Solution:
I. Session read and write
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
II. URL rewriting sending and retrieving parameter(s)
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-24
Writing links
<a href="store/catalog">
is rewritten as
<a href="store/catalog;$jsessionid$DA32242SSGE2">
<%
response.encodeURL ("/store/catalog");
%>
out.println("<a href=\"/store/catalog\">catalog</a>")"
replace it with
out.println("<a href=\"");
out.println(response.encodeURL ("/store/catalog"));
out.println("\">catalog</a>");
Writing forms:-
To write forms for submission, call the
response.encodeURL("Logon"); on the ACTION tag of
the form page. For example:
<FORM NAME="Logon" METHOD="post" ACTION= <%=
response.encodeURL ("Logon")
%> >
... </FORM>
III. URL redirection
String site = new String("http://www.photofuntoos.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
IV. Print “hello world” as output
<html>
<head><title>Hello World JSP Page.</title></head>
<body>
<font size="10"><%="Hello World!" %></font>
</body>
</html>
V. Include the other JSP file statically
<%@ include file="banner.jsp" %>
VI. Expression to display date as output
<%= new java.util.Date() %>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-25
OR
Q.4 (a) Explain event handling in Java Servlet with example(s). 07
Solution:
Event handling in Servlets
When a request is mapped to a servlet, the Web container creates
the instance of the servlet
class and then initializes the servlet by calling the init() method. Once
the init() method is
executed, the service() method gets executed with the Request and
Response parameters.
After the service() method execution, the web container may call the
destroy method if the
Web container does not require the servlet.
Different events of the Servlet life cycle can now received and
particular methods can be
called on the basis of these event. Depending on the type of event, a
listener class (context
listener or session listener or request listener) is defined.
Following events can occur with Servlets
1. Initializing and destroying Servlets
2. Adding, removing or replacing attributes in Servlet Context
3. Creating, activating, passivating or invalidating a session
4. Adding, removing or replacing attributes in a Servlet session
5. When a request is coming and going out of Servlet scope
Context Listeners are used to notify a class when the context is
initialized or destroyed or
when an attribute is added or removed to the web context.
Session Listeners are used to notify a class when the session is
initialized, destroyed,
activated, passivated or when an attribute is added, replaced or
removed.
Request Listeners are used to notify a class when the request is
coming into scope for a
servlet or the request is getting out of scope for a servlet. A request
is defined as coming into
scope when it is about to enter the first servlet or servlet filter.
Types of Servlet Events
Request Level events: There are two event listeners for request level
events
● ServletRequestListener interface is implemented to notify the
request coming in scope
and going out of scope for a servlet.
● ServletRequestAttributeListener interface is implemented to notify
the changes
(addition, replacement or removal) in the request attributes.
Servlet Context Level events:
There are two event listeners for Servlet Context level events
● ServletContextListener interface is implemented to notify the
initialization or
destruction of the Servlet.
● ServletContextAttributeListener interface is implemented to notify
the changes
(addition, replacement or removal) in the Servlet Context attributes
Servlet Session Level events:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-26
The Servlet session level events refer to events that are used to
maintain the client’s session.
There are four event listeners for Servlet Session level events
● HttpSessionListener interface is implemented to notify the
initialization or destruction
of the Http Session. See the HttpSessionListener example
● HttpSessionActivationListener interface is implemented to notify
when a sessions
object migrates from one VM to another. The
HttpSessionActivationListener only has
any relevance when a session is part of a web application in a
distributed environment.
When a session is activated, notification that the session has just
been activated will
be received by the SessionDidActivate method and when the session
is about to be
destroyed, the sessionWillPassivate method is invoked. When the
session migrates
between servers, the sessionWillPassivate is called and once it is
successfully moved,
the sessionDidActivate will be called. It is interesting to note that the
sesssion is not
yet ready for service at the time the sessionDidActivate method is
called. See example
for implementing HttpSessionActivationListener
● HttpSessionAttributeListener interface is implemented to notify the
changes (addition,
replacement or removal) in the HttpSession attributes
Example:-
import javax.servlet.*;
import java.sql.*;
import javax.sql.*;
import org.apache.derby.jdbc.*;
public final class ContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent ev) {
ServletContext context = ev.getServletContext();
try {
DataSource dataSource = new DataSource();
context.setAttribute("datasource", dataSource);
} catch (Exception ex) {
ex.printStackTrace();
}
Integer hits = new Integer(0);
context.setAttribute("hits", hits);
//context.log("Created hitCounter" + counter.getCounter());
}
public void contextDestroyed(ServletContextEvent event) {
ServletContext context = event.getServletContext();
DataSource dataSource = context.getAttribute("datasource");
dataSource.close();
context.removeAttribute("datasource");
context.removeAttribute("hits");
}
private DataSource createDataSource() {
ClientDataSource datasource = new
org.apache.derby.jdbc.ClientDataSource();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-27
datasource.setServerName("localhost");
datasource.setPortNumber(12345);
datasource.setDatabaseName("mydb");
}
}
Q.4 (b) Enlist and explain the purpose and use of action tags in JSP.
07
Solution:
Action tags are a set of some basic tags, such as inserting other
page resources, forwarding
the request to another page, creating and locating the JavaBeans
instances, and setting and
retrieving bean properties, in JSP pages. Instead of using Java code,
the programmer uses
special JSP action tags to either link to a Java Bean set its
properties, or get its properties.
These are the most commonly used action tags are :
1. include
2. forward
3. param
4. useBean
5. setProperty
6. getProperty
In this article I described the first three action tags, the next three
action tags will be described
in the next article.
Describing the Include Tag: The include action tag allows a static or
dynamic resource
such as HTML or JSP pages, specified by a URL, to be included in
the current JSP while
processing a request.Include action tag is almost similar to include
directive. This include can
be static or dynamic. This include file is first compiled and output of
this file is inserted with
parent file. The following code snippet shows the syntax of the
include action :
<jsp: include attributes>
<!--zero or more jsp: param tags-->
</jsp: include>
Difference Between Include Directive and Include action:
Include Directive: The 'include' directive tag inserts the given page
and includes content in the
generated Servlet page during the translation phase of the JSP life
cycle. It is generally used
to include files, such as HTML, JSP, XML .txt file, into a JSP page
statically. The snippet code
use for it is:
<%@ include file= "index.jsp" %>
Include Action: The 'include' action tag is used to include the
response generated by
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-28
executing the specified JSP page or Servlet. Unlike the include
directive tag, the include
action tag accepts expressions. we can decide the page to be
included at runtime, whereas it
is not possible with the include directive tag. The snippet code use
for it is:
<jsp: include page= "index.jsp">
Describing the Forward Tag: The jsp:forward tag forwards the
request to another resource.
The resource can be dynamic or static. When we use param tags, it
is dynamic forward
with having values. Static forward is simple forward without having
param tags. Forward is
used when we need to jump from one page to another if error occur
or if work is completed in
parent page. The following code snippet shows the syntax of the
forward action:
<jsp:forward attributes>
<!--zero or more jsp: param tags-->
</jsp:forward>
Like:<jsp:forward page= "Header.html"/>
Describing the Param Tag: The jsp:param tag allows us to pass a
name and value pair as
parameter to a dynamic resource, while including and forwarding the
jsp page to another jsp
page. we can use more than one param tag if we want to pass more
than one parameter. The
following code snippet shows the syntax of the param action :
<jsp:param attributes />
Q.5 (a) Explain transaction handling using JSTL. 07
Solution:
The <sql:transaction> tag is used to group <sql:query> and
<sql:update> into transactions.
You can put as many <sql:query> and <sql:update> as statements
inside <sql:transaction> to
make them a single transaction.
It ensures that the database modifications performed by the nested
actions are either
committed or rolled back if an exception is thrown by any nested
action.
The <sql:transaction> tag has following attributes:
Attribute Description Required Default
dataSource Database connection to use (overrides the
default)
No Default
database
isolation Transaction isolation (READ_COMMITTED,
READ_UNCOMMITTED,
REPEATABLE_READ, or SERIALIZABLE)
No Database’s
default
To start with basic concept, let us create a simple table Students
table in TEST database and
create few records in that table as follows:
Step 1:
Open a Command Prompt and change to the installation directory as
follows:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-29
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2:
Login to database as follows
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Step 3:
Create the table Employee in TEST database as follows:
mysql> use TEST;
mysql> create table Students
(
id int not null,
first varchar (255),
last varchar (255),
dob date
);
Query OK, 0 rows affected (0.08 sec)
mysql>
Create Data Records
Finally you create few records in Employee table as follows:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-30
mysql> INSERT INTO Students
VALUES (100, 'Zara', 'Ali', '2002/05/16');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Students
VALUES (101, 'Mahnaz', 'Fatma', '1978/11/28');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Students
VALUES (102, 'Zaid', 'Khan', '1980/10/10');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Students
VALUES (103, 'Sumit', 'Mittal', '1971/05/08');
Query OK, 1 row affected (0.00 sec)
mysql>
Now let us write a JSP which will make use of <sql:update> along
with <sql:transaction>
to execute a SQL UPDATE statement. Here code inside
<sql:transaction> either would be
exeucted completely or not at all:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-31
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<%@ page import="java.util.Date,java.text.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>JSTL sql:transaction Tag</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="cohondob"/>
<%
Date DoB = new Date("2001/12/16");
int studentId = 100;
%>
<sql:transaction dataSource="${snapshot}">
<sql:update var="count">
UPDATE Students SET last = 'Ali' WHERE Id = 102
</sql:update>
<sql:update var="count">
UPDATE Students SET last = 'Shah' WHERE Id = 103
</sql:update>
<sql:update var="count">
INSERT INTO Students
VALUES (104,'Nuha', 'Ali', '2010/05/26');
</sql:update>
</sql:transaction>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Students;
</sql:query>
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DoB</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.dob}"/></td>
</tr>
</c:forEach>
</table>
</body>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-32
(b) Write a note on hibernate. 07
Solution:
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA
and it raised as an open
source persistent framework created by Gavin King in 2001. It is a
powerful, high performance
Object-Relational Persistence and Query service for any Java
Application.
Hibernate maps Java classes to database tables and from Java data
types to SQL data types
and relieve the developer from 95% of common data persistence
related programming tasks.
Hibernate sits between traditional Java objects and database server
to handle all the work in
persisting those objects based on the appropriate O/R mechanisms
and patterns.
Hibernate Advantages:
● Hibernate takes care of mapping Java classes to database tables
using XML files and
without writing any line of code.
● Provides simple APIs for storing and retrieving Java objects directly
to and from the
database.
● If there is change in Database or in any table then the only need to
change XML file
properties.
● Abstract away the unfamiliar SQL types and provide us to work
around familiar Java
Objects.
● Hibernate does not require an application server to operate.
● Manipulates Complex associations of objects of your database.
● Minimize database access with smart fetching strategies.
● Provides Simple querying of data.
Supported Databases:
Hibernate supports almost all the major RDBMS. Following is list of
few of the database
engines supported by Hibernate.
● HSQL Database Engine
● DB2/NT
● MySQL
● PostgreSQL
● FrontBase
● Oracle
● Microsoft SQL Server Database
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-33
● Sybase SQL Server
● Informix Dynamic Server
Supported Technologies:
Hibernate supports a variety of other technologies, including the
following:
● XDoclet Spring
● J2EE
● Eclipse plug-ins
● Maven
OR
Q.5 (a) Write a JSTL program to parse & display text of XML file. 07
Solution:-
<?xml version="1.0" encoding="ISO-8859-1"?>
<students>
<student id="1">
<name>
<first>Joe</first>
<last>Y</last>
<middle>T</middle>
</name>
<grade>
<points>99</points>
<letter>A</letter>
</grade>
</student>
<student id="2">
<name>
<first>James</first>
<last>Todd</last>
<middle>K</middle>
</name>
<grade>
<points>92</points>
<letter>B</letter>
</grade>
</student>
<student id="3">
<name>
<first>Kate</first>
<last>Wang</last>
<middle>A</middle>
</name>
<grade>
<points>72</points>
<letter>C</letter>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-34
</grade>
</student>
</students>
///////////////////////////////////////////////////////////////////////////////
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/xml" prefix="x" %>
<html>
<head>
<title>Parse Examples</title>
</head>
<body>Please enter an XML file:
<br />
<form method="post">
<textarea rows="10" cols="50" name="xml">
<students>
<student id="1">
<name>
<first>John</first>
<last>Smith</last>
<middle>T</middle>
</name>
<grade>
<points>88</points>
<letter>B</letter>
</grade>
</student>
<student id="2">
<name>
<first>James</first>
<last>Smith</last>
<middle>K</middle>
</name>
<grade>
<points>92</points>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-35
<letter>A</letter>
</grade>
</student>
<student id="3">
<name>
<first>Kelly</first>
<last>Lane</last>
<middle>A</middle>
</name>
<grade>
<points>72</points>
<letter>C</letter>
</grade>
</student>
</students>
</textarea>
<br />
<input type="submit" />
</form>
<c:if test="${pageContext.request.method=='POST'}">
<x:parse var="doc" xml="${param.xml}" />
<table border="1">
<tr>
<td>$doc/students/student/name/first</td>
<td>
<x:out select="$doc/students/student/name/first" />
</td>
</tr>
<tr>
<td>$doc/students/student[@id=2]/name/first</td>
<td>
<x:out
select="$doc/students/student[@id=2]/name/first" />
</td>
</tr>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-36
<tr>
<td>$doc/students/student[@id=1]/name/first</td>
<td>
<x:out
select="$doc/students/student[@id=12]/name/first" />
</td>
</tr>
</table>
</c:if>
</body>
</html>
(b) Write a JDBC program to insert and retrieve photo in databse. 07
Solution:
BLOB(Binary Large Object) or CLOB(Character Large Object) are
used to store an image into
database. To store an image into database you need to use other
than JDBC-ODBC driver .
since JDBC-ODBC driver does not support BLOB/CLOB. In my case
am using "thin" driver,
you can download the thin driver(jar file) and place it in your
classpath.
Create a table to store an image
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE",
"system", // User here
"system" // Password here
);
Statement stmt=con.createStatement();
stmt.execute("Create table img(no number,photo blob)");
Inserting Image into Database
File file=new File("f:/dp.jpg"); //image path
FileInputStream fis=new FileInputStream(file);
long lenx=file.length();
byte [] b=new byte[(int)lenx];
fis.read(b);
String str="insert into img values(?,?)";
PreparedStatement ps=con.prepareStatement(str);
ps.setInt(1,1);
ps.setBytes(2,b);
ps.execute();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-37
Retrieving Image from Database
ResultSet rs=stmt.executeQuery("select photo from img1 where
no=1");
while(rs.next())
{
byte[] fileBytes = rs.getBytes(1);
OutputStream targetFile = new
FileOutputStream("e:/dp.jpg");//destination path
targetFile.write(fileBytes);
targetFile.close();
}
Advance Java Technology
Term: WINTER 2012 Subject code: 170703 Date: 07-12-2013
Q.1 (a) What is pluggable look and feel? What is its importance?
Assume that an
application contains a textfield and a button. Show that how to apply
plaf of your
choice to them. 07
Solution:
::Pluggable Look and Feel and its Importance:-
The Java Swing API provides a pluggable look-and-feel (PLAF)
capability, which allows Swing
GUI widgets to change appearance based on the programmer's
customized look-and-feel
setting. Almost all modern user interface frameworks coalesce the
view and controller, whether
they are based on SmallTalk, C++, or Java.
Swing packages each component's view and controller into an object
called a UI delegate.
For this reason, Swing's underlying architecture is referred to as
model-delegate rather than a
model-view-controller. Ideally, communication between both the
model and the UI delegate is
indirect, allowing more than one model to be associated with one UI
delegate and vice versa
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-38
Example:-
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import Malachite.*;
public class Button1 extends JFrame
{
protected Hashtable m_lfs;
public Button1() {
super("Look and Feel [Resources]");
setSize(400, 300);
getContentPane().setLayout(new FlowLayout());
JButton bt1 = new JButton("Click Me");
p.add(bt1);
JTextArea txt = new JTextArea(5, 30);
getContentPane().add(txt);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
}
public static void main(String argv[]) {
try {
LookAndFeel malachite = new Malachite.MalachiteLF();
UIManager.LookAndFeelInfo info =
new UIManager.LookAndFeelInfo(malachite.getName(),
malachite.getClass().getName());
UIManager.installLookAndFeel(info);
UIManager.setLookAndFeel(malachite);
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.toString());
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-39
new Button1(); //calling the class
}}
(b) Explain following in brief: (1) MVC and (2) JDBC Architecture 07
:: MVC:-
Model View Controller or MVC as it is popularly called, is a software
design pattern for
developing web applications. A Model View Controller pattern is
made up of the following three
parts:
● Model - The lowest level of the pattern which is responsible for
maintaining data.
● View - This is responsible for displaying all or a portion of the data
to the user.
● Controller - Software Code that controls the interactions between
the Model and View.
MVC is popular as it isolates the application logic from the user
interface layer and supports
separation of concerns. Here the Controller receives all requests for
the application and then
works with the Model to prepare any data needed by the View. The
View then uses the data
prepared by the Controller to generate a final presentable response.
The MVC abstraction can
be graphically represented as follows.
The model
The model is responsible for managing the data of the application. It
responds to the request
from the view and it also responds to instructions from the controller
to update itself.
The view
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-40
A presentation of data in a particular format, triggered by a
controller's decision to present the
data. They are script based templating systems like JSP, ASP, PHP
and very easy to integrate
with AJAX technology.
The controller
The controller is responsible for responding to user input and perform
interactions on the data
model objects. The controller receives the input, it validates the input
and then performs the
business operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us
see how we can use the
MVC methodology within Struts2.
:: JDBC Architecture:-
A JDBC application is composed of multiple layers, as shown in
Figure
JDBC architecture
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-41
The topmost layer in this model is the Java application. Java
applications are portable?you can
run a Java application without modification on any system that has a
Java runtime environment
installed. A Java application that uses JDBC can talk to many
databases with few, if any,
modifications. Like ODBC, JDBC provides a consistent way to
connect to a database, execute
commands, and retrieve the results. Also like ODBC, JDBC does not
enforce a common
command language?you can use Oracle-specific syntax when
connected to an Oracle server
and PostgreSQL-specific syntax when connected to a PostgreSQL
server. If you stick to a
common subset, you can achieve remarkable portability for your
applications.
The JDBC DriverManager
The JDBC DriverManager class is responsible for locating a JDBC
driver needed by the
application. When a client application requests a database
connection, the request is
expressed in the form of a URL (Uniform Resource Locator). A
typical URL might look like
jdbc:postgresql:movies.
The JDBC Driver
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-42
As each driver is loaded into a Java Virtual Machine (VM), it registers
itself with the JDBC
DriverManager. When an application requests a connection, the
DriverManager asks each
Driver whether it can connect to the database specified in the given
URL. As soon as it finds
an appropriate Driver, the search stops and the Driver attempts to
make a connection to
the database. If the connection attempt fails, the Driver will throw a
SQLException to the
application. If the connection completes successfully, the Driver
creates a Connection object
and returns it to the application.
The JDBC 2.0 architecture introduced another method for
establishing database connections:
the Data Source. A Data Source is a named collection of connection
properties that can be used
to load a Driver and create a Connection. I do not discuss the
DataSource class in this chapter
because it is not yet part of the J2SE (Java 2 Standard Edition)
standard; the DataSource class
is a component of J2EE (Java 2 Enterprise Edition). The PostgreSQL
JDBC driver does support
the DataSource class.
The JDBC-Compliant Database
The bottom layer of the JDBC model is the database. The
PostgreSQL Driver class (and
other JDBC classes) translates application commands into
PostgreSQL network requests and
translates the results back into JDBC object form.
Q.2 (a) What is container in Java EE 6? Give its architecture and
discuss its role
in
hosting the applications. 07
Solution:
::Container in Java EE6:-
Normally, thin-client multitiered applications are hard to write
because they involve many lines
of intricate code to handle transaction and state management,
multithreading, resource pooling,
and other complex low-level details. The component-based and
platform-independent Java EE
architecture makes Java EE applications easy to write because
business logic is organized into
reusable components. In addition, the Java EE server provides
underlying services in the form
of a container for every component type. Because you do not have to
develop these services
yourself, you are free to concentrate on solving the business problem
at hand.
Container Services
Containers are the interface between a component and the low-level
platform-specific
functionality that supports the component. Before it can be executed,
a web, enterprise bean, or
application client component must be assembled into a Java EE
module and deployed into its
container.
The assembly process involves specifying container settings for each
component in the
Java EE application and for the Java EE application itself. Container
settings customize
the underlying support provided by the Java EE server, including
such services as security,
transaction management, Java Naming and Directory Interface
(JNDI) API lookups, and remote
connectivity. Here are some of the highlights.
● The Java EE security model lets you configure a web component
or enterprise bean so
that system resources are accessed only by authorized users.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-43
● The Java EE transaction model lets you specify relationships
among methods that make
up a single transaction so that all methods in one transaction are
treated as a single unit.
● JNDI lookup services provide a unified interface to multiple naming
and directory
services in the enterprise so that application components can access
these services.
● The Java EE remote connectivity model manages low-level
communications between
clients and enterprise beans. After an enterprise bean is created, a
client invokes
methods on it as if it were in the same virtual machine.
Because the Java EE architecture provides configurable services,
application components
within the same Java EE application can behave differently based on
where they are deployed.
For example, an enterprise bean can have security settings that
allow it a certain level of access
to database data in one production environment and another level of
database access in
another production environment.
Figure Java EE Server and Containers
● Java EE server: The runtime portion of a Java EE product. A Java
EE server provides
EJB and web containers.
● Enterprise JavaBeans (EJB) container: Manages the execution of
enterprise beans for
Java EE applications. Enterprise beans and their container run on
the Java EE server.
● Web container: Manages the execution of web pages, servlets, and
some EJB
components for Java EE applications. Web components and their
container run on the
Java EE server.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-44
● Application client container: Manages the execution of application
client components.
Application clients and their container run on the client.
● Applet container: Manages the execution of applets. Consists of a
web browser and
Java Plug-in running on the client together.
:: Role of Container as in Context of Hosting:-
The primary role of the web container is to provide a run-time
environment for web applications
and provide services (database access, security, multi-threading, and
so on) to web applications
hosted in the container. A web application is a collection of servlets,
HTML pages, classes, and
other resources that make up a complete application on Sun Java
System Application Server.
The following are the elements of a web application:
● Servlets
● JSP pages
● Utility classes
● Static documents (html, images, sound files, etc.)
● Client side Java applets, beans, and classes
● Descriptive meta information which ties all of the above elements
together.
Web applications may be deployed in the web containers running in
a Sun Java System
Application Server.
(b) What is CallableStatement? Show that how to use it to call a
stored procedure
running at database layer. 07
Solution:-
Just as a Connection object creates the Statement and
PreparedStatement objects, it also
creates the CallableStatement object which would be used to
execute a call to a database
stored procedure.
Callable Statement with Example:-
Creating CallableStatement Object to Create and Call Stored
Procedure:
Suppose, you need to execute the following Oracle stored procedure:
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-45
WHERE ID = EMP_ID;
END
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The
PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all
three.
Here are the definitions of each:
Parameter Description
IN A parameter whose value is unknown when the SQL
statement is created. You bind values to IN parameters with
the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it
returns. You retrieve values from theOUT parameters with the
getXXX() methods.
INOUT A parameter that provides both input and output values. You
bind variables with the setXXX() methods and retrieve values
with the getXXX() methods.
The following code snippet shows how to employ the
Connection.prepareCall() method to
instantiate a CallableStatement object based on the preceding stored
procedure:
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}finally { . . .
}
OR
(b) Write a complete RMI application with interface, server object and
client to
compute the area of a circle where client provides the radius.
Solution:
import java.rmi.*;
public interface Circle extends Remote {
public double findArea(double radius)throws RemoteException;
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-46
//This is my server
import java.rmi.*;
import java.rmi.server.*;
public class CircleEngine extends UnicastRemoteObject implements
Circle {
public CircleEngine() throws RemoteException{
super();
}
public double findArea(double radius) throws RemoteException {
return radius*radius*Math.PI;
}
public static void main(String[] args) {
if(System.getSecurityManager()== null){
System.setSecurityManager(new RMISecurityManager());
}
try{
Circle circle = new CircleEngine();
String url = "rmi://10.0.4.37:1024/";
Naming.rebind(url,circle);
System.out.println("Remote Object"+circle+"bound");
}
catch(Exception ex){
System.out.println("Circle Exception"+ex.getMessage());
ex.printStackTrace();
}}}
//This is my client
import java.rmi.*;
import javax.swing.*;
public class Client {
public static void main(String[] args) {
if(System.getSecurityManager()==null){
System.setSecurityManager(new RMISecurityManager());
}
String input = JOptionPane.showInputDialog("Enter radius");
double radius = Double.parseDouble(input);
try{
String url = "rmi://10.0.4.37:1024/Circle";
Circle circle = (Circle)Naming.lookup(url);
System.out.println("Remote object"+circle+"found");
double area = (double)circle.findArea(radius);
System.out.println(area);
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-47
catch(Exception ex){
System.err.println(ex);
}}
}
Q.3 (a) Discuss the URL and URLConnection class with their use in
network
programming. 07
Solution:
URLConnection class:
The 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.
How to get the object of URLConnection class:
The openConnection() method of URL class returns the object of
URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
}
Displaying all the data of a webpage by URLConnecton class
The URLConnection class provides many methods, we can display
all the data of a webpage
by using the getInputStream() method. The getInputStream() method
returns all the data of
the specified URL in the stream that can be read and displayed.
Example of Displaying all the data of a webpage by URLConnecton
class:
1. //DisplayData.java
import java.io.*;
import java.net.*;
public class DisplayData {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/sonoojaiswal/");
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-48
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);}
}
}
(b) What are cookies and sessions? How can you use them in Java
EE? Compare
them. 07
Solution:
::Session:-
HTTP protocol and Web Servers are stateless, what it means is that
for web server every
request is a new request to process and they can’t identify if it’s
coming from client that has
been sending request previously.
But sometimes in web applications, we should know who the client is
and process the request
accordingly. For example, a shopping cart application should know
who is sending the request
to add an item and in which cart the item has to be added or who is
sending checkout request
so that it can charge the amount to correct client.
Session is a conversional state between client and server and it can
consists of multiple request
and response between client and server. Since HTTP and Web
Server both are stateless, the
only way to maintain a session is when some unique information
about the session (session id)
is passed between server and client in every request and response.
There are several ways through which we can provide unique
identifier in request and response.
1. User Authentication – This is the very common way where we user
can provide
authentication credentials from the login page and then we can pass
the authentication
information between server and client to maintain the session. This is
not very effective
method because it wont work if the same user is logged in from
different browsers.
2. HTML Hidden Field – We can create a unique hidden field in the
HTML and when user
starts navigating, we can set its value unique to the user and keep
track of the session.
This method can’t be used with links because it needs the form to be
submitted every
time request is made from client to server with the hidden field. Also
it’s not secure
because we can get the hidden field value from the HTML source
and use it to hack the
session.
3. URL Rewriting – We can append a session identifier parameter
with every request and
response to keep track of the session. This is very tedious because
we need to keep
track of this parameter in every response and make sure it’s not
clashing with other
parameters.
4. Cookies – Cookies are small piece of information that is sent by
web server in response
header and gets stored in the browser cookies. When client make
further request, it
adds the cookie to the request header and we can utilize it to keep
track of the session.
We can maintain a session with cookies but if the client disables the
cookies, then it
won’t work.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-49
5. Session Management API – Session Management API is built on
top of above methods
for session tracking.
:: Cookies:-
Cookies are used a lot in web applications to personalize response
based on your choice or to
keep track of session. Before moving forward to the Servlet Session
Management API, I would
like to show how can we keep track of session with cookies through a
small web application.
:: Code that demonstrate Session and Cookie:-
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "Pankaj";
private final String password = "journaldev";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
Cookie loginCookie = new Cookie("user",user);
//setting cookie to expiry in 30 mins
loginCookie.setMaxAge(30*60);
response.addCookie(loginCookie);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-50
out.println("<font color=red>Either user name or password is
wrong.</font>");
rd.include(request, response);
}
}
}
:: Difference between Session and Cookie:-
Session is stored in server but cookie stored in client. Session should
work regardless of the
settings on the client browser. There is no limit on the amount of data
that can be stored on
session. But it is limited in cookie. Session can store objects and
cookies can store only strings.
Cookies are faster than session.
OR
Q.3 (a) Write a web application using servlet to compute an area of a
circle. Get the
radius from the client. Write necessary web.xml file. 07
Solution:
JSP Page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"><%@page
language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>index</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
</head>
<body>
<form action="Process" method="get">
<input type="text" name="rad"/>
<input type="submit" value="Area” name="action"/>
</form>
<br/>
<hr/>
<p>The result is :<%=request.getAttribute("result") %></p>
</body>
</html>
Servlet Code:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
int op1=Integer.parseInt((String)request.getAttribute("rad"));
int result=3.14*rad*rad;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-51
request.setAttribute("result", new Integer(result));
RequestDispatcher
dispatcher=request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
return;
}
(b) What is servlet filters? Give the necessary API for filters and
explain their use. 07
Servlet Filters are Java classes that can be used in Servlet
Programming for the following
purposes:
● To intercept requests from a client before they access a resource
at back end.
● To manipulate responses from server before they are sent back to
the client.
There are are various types of filters suggested by the specifications:
● Authentication Filters.
● Data compression Filters.
● Encryption Filters.
● Filters that trigger resource access events.
● Image Conversion Filters.
● Logging and Auditing Filters.
● MIME-TYPE Chain Filters.
● Tokenizing Filters .
● XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and
then map to either servlet
names or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an
instance of each filter that
you have declared in the deployment descriptor. The filters execute
in the order that they are
declared in the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter
interface. The
javax.servlet.Filter interface defines three methods:
S.N. Method & Description
1 public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method is called by the container each time a request/response
pair is passed
through the chain due to a client request for a resource at the end of
the chain.
2 public void init(FilterConfig filterConfig)
This method is called by the web container to indicate to a filter that it
is being placed
into service.
3 public void destroy()
This method is called by the web container to indicate to a filter that it
is being taken
out of service.
Servlet Filter Example:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-52
Following is the Servlet Filter Example that would print the clients IP
address and
current date time. This example would give you basic understanding
of Servlet Filter,
but you can write more sophisticated filter applications using the
same concept:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Implements Filter class
public class LogFilter implements Filter {
public void init(FilterConfig config)
throws ServletException{
// Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
// Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
// Log the IP address and current timestamp.
System.out.println("IP "+ ipAddress + ", Time "
+ new Date().toString());
// Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy( ){
/* Called before the Filter instance is removed
from service by the web container*/
}
}
Servlet Filter Mapping in Web.xml:
Filters are defined and then mapped to a URL or Servlet, in much the
same way as
Servlet is defined and then mapped to a URL pattern. Create the
following entry for
filter tag in the deployment descriptor file web.xml
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-53
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Q.4 (a) Describe following with proper illustrations:
(1) Type-4 JDBC driver (2) Servlet events 07
:: Type-4 JDBC driver :-
In a Type 4 driver, a pure Java-based driver that communicates
directly with vendor's database
through socket connection. This is the highest performance driver
available for the database
and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install
special software on the client or
server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the
proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
::Servlet events:-
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-54
Events are basically occurrence of something. Changing the state of
an object is known as
an event.
We can perform some important tasks at the occurrence of these
exceptions, such as
counting total and current logged-in users, creating tables of the
database at time of
deploying the project, creating database connection object etc.
There are many Event classes and Listener interfaces in the
javax.servlet and
javax.servlet.http packages.
Event classes
The event classes are as follows:
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
Event interfaces
The event interfaces are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener
(b) Explain the JSP core tag library. 07
The JavaServer Pages Standard Tag Library (JSTL) is a collection of
useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and
conditionals, tags for
manipulating XML documents, internationalization tags, and SQL
tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into
following JSTL tag library
groups that can be used when creating a JSP page:
● Core Tags
● Formatting tags
● SQL tags
● XML tags
● JSTL Functions
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-55
Core Tags:
The core group of tags are the most frequently used JSTL tags.
Following is the syntax to
include JSTL Core library in your JSP:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:set > Sets the result of an expression evaluation in a 'scope'
<c:remove > Removes a scoped variable (from a particular scope, if
specified).
<c:catch> Catches any Throwable that occurs in its body and
optionally
exposes it.
<c:if> Simple conditional tag which evalutes its body if the supplied
condition is true.
<c:choose> Simple conditional tag that establishes a context for
mutually
exclusive conditional operations, marked by <when> and
<otherwise>
<c:when> Subtag of <choose> that includes its body if its condition
evalutes to 'true'.
<c:otherwise > Subtag of <choose> that follows <when> tags and
runs only if
all of the prior conditions evaluated to 'false'.
<c:import> Retrieves an absolute or relative URL and exposes its
contents
to either the page, a String in 'var', or a Reader in 'varReader'.
<c:forEach > The basic iteration tag, accepting many different
collection types
and supporting subsetting and other functionality .
<c:forTokens> Iterates over tokens, separated by the supplied
delimeters.
<c:param> Adds a parameter to a containing 'import' tag's URL.
<c:redirect > Redirects to a new URL.
<c:url> Creates a URL with optional query parameters
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-56
OR
Q.4 (a) Show the use of JSP inbuilt objects: request and response,
with their use in
application. 07
The HttpServletResponse Object:
The response object is an instance of a
javax.servlet.http.HttpServletResponse object. Just as
the server creates the request object, it also creates an object to
represent the response to the
client.
The response object also defines the interfaces that deal with
creating new HTTP headers.
Through this object the JSP programmer can add new cookies or
date stamps, HTTP status
codes etc.
There are following methods which can be used to set HTTP
response header in your servlet
program. These method are available with HttpServletResponse
object which represents server
response.
S.N. Method & Description
1 String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if
encoding is not
needed, returns the URL unchanged.
2 String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if
encoding is not
needed, returns the URL unchanged.
3 boolean containsHeader(String name)
Returns a boolean indicating whether the named response header
has already been
set.
4 boolean isCommitted()
Returns a boolean indicating if the response has been committed.
5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6 void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7 void addHeader(String name, String value)
Adds a response header with the given name and value.
8 void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-57
9 void flushBuffer()
Forces any content in the buffer to be written to the client.
10 void reset()
Clears any data that exists in the buffer as well as the status code
and headers.
11 void resetBuffer()
Clears the content of the underlying buffer in the response without
clearing headers or
status code.
12 void sendError(int sc)
Sends an error response to the client using the specified status code
and clearing the
buffer.
13 void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14 void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified
redirect location
URL.
15 void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16 void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being
sent to the client,
for example, to UTF-8.
17 void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets,
this method
sets the HTTP Content-Length header.
18 void setContentType(String type)
Sets the content type of the response being sent to the client, if the
response has not
been committed yet.
19 void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
20 void setHeader(String name, String value)
Sets a response header with the given name and value.
21 void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22 void setLocale(Locale loc)
Sets the locale of the response, if the response has not been
committed yet.
23 void setStatus(int sc)
Sets the status code for this response.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-58
HTTP Header Response Example:
Following example would use setIntHeader() method to set Refresh
header to simulate a digital
clock:
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Current Time is: " + CT + "\n");
%>
</center>
</body>
</html>
(b) Explain the JSP XML tag library. 07
The JSTL XML tags provide a JSP-centric way of creating and
manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML
data. This includes parsing
XML, transforming XML data, and flow control based on XPath
expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy
following two XML and
Following is the list of XML JSTL Tags:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-59
<x:parse> Use to parse XML data specified either via an attribute or
in the
tag body.
<x:set > Sets a variable to the value of an XPath expression.
<x:if > Evaluates a test XPath expression and if it is true, it processes
its body. If the test condition is false, the body is ignored.
<x:forEach> To loop over nodes in an XML document.
<x:choose> Simple conditional tag that establishes a context for
mutually
exclusive conditional operations, marked by <when> and
<otherwise>
<x:when > Subtag of <choose> that includes its body if its expression
evalutes to 'true'
<x:otherwise > Subtag of <choose> that follows <when> tags and
runs only if
all of the prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
<x:param > Use along with the transform tag to set a parameter in
the XSLT
stylesheet
Q.5 (a) What is servlet configuration? Show it with example web.xml
file. 07
Sometimes it is necessary to provide initial configuration information
for Servlets. Configuration
information for a Servlet may consist of a string or a set of string
values included in the Servlet's
web.xml declaration. This functionality allows a Servlet to have initial
parameters specified
outside of the compiled code and changed without needing to
recompile the Servlet. Each
servlet has an object associated with it called the ServletConfig19.
This object is created by
the container and implements the javax.servlet.ServletConfig
interface. It is the ServletConfig
that contains the initialization parameters. A reference to this object
can be retrieved by calling
the getServletConfig() method. The ServletConfig object provides the
following methods for
accessing initial parameters:
getInitParameter(String name)
The getInitParameter() returns a String object that contains the value
of the named initialization
parameter or null if the parameter does not exist.
getInitParameterNames()
The getInitParameterNames() method returns the names of the
Servlet's initialization
parameters as an Enumeration of String objects or an empty
Enumeration if the Servlet has no
initialization parameters.
Defining initial parameters for a Servlet requires using the init-param,
param-name, and paramvalue
elements in web.xml. Each init-param element defines one initial
parameter and must
contain a parameter name and value specified by children param-
name and param-value
elements, respectively. A Servlet may have as many initial
parameters as needed, and initial
parameter information for a specific Servlet should be specified
within the servlet element for
that particular Servlet.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-60
Setting thats should be applied on XML file:-
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.jspbook.HelloWorld</servlet-class>
</servlet>
<servlet>
<servlet-name>InternationalizedHelloWorld</servlet-name>
<servlet-class>
com.jspbook.InternationalizedHelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InternationalizedHelloWorld</servlet-name>
<url-pattern>/InternationalizedHelloWorld</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
</web-app>
(b) Give and explain the architecture of Hibernate. 07
It is layered architecture. So you are away from the underlying APIs.
Hibernate is written in java
and you can configure it in two waysfirst
by using configuration file named hibernate.cfg.xml and another by
using *.hbm.
Diagram : Here is diagram of Hibernate architecture.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-61
The above diagram shows how hibernate uses database and
configuration data to provide
persistent object to your application.
JDBC is not the only technology used between Hibernate and
database server but there are
more java APIs like JTA(Java Transaction API),JNDI(Java Naming
and Directory Interface).
Now we are going to give you brief description of architecture -
Hibernate Configuration :
Configuration class perform two operations. You can say
Configuration class has two
component-database connection and class mapping setup.
The first component is handled through one or more configuration
files supported by Hibernate.
These files are hibernate properties and hibernate.cfg.xml.
Second component that is class mapping, it creates the connection
between java classes and
database tables.
Hibernate SessionFactory :
For SessionFactory import org.hibernate.SessionFactory.
SessionFactory is factory for
Sessions and is created in your configuration file.
When your application start ,it is created. For each database ,there is
one SessionFactory.
If you are using more than one database you need to create multiple
SessionFactory object. It is
thread safe object.
It also maintains second level cache of data that is reusable between
transactions at a process
or cluster level but it is optional.
Hibernate Session :
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-62
For Session Object import org.hibernate.Session. It is used for
database connection. It is very
lightweight and
single-threaded. It lives for short time, represents conversation
between the application and the
persistent store.
Session object is used for saving and retrieving persistent objects.
Session object is not thread
safe so do not open it for long time.
You can create and destroy as your need.
Hibernate Transaction :
For Transaction import class org.hibernate.Transaction.It is optional.
Transaction is single threaded and short-lived object ,used for a unit
of work with the database.
Most of the RDBMS supports transaction functionality. Transaction
manager handle your
transactions.
Hibernate Query :
Hibernate provide simple SQL ,native query and HQL for performing
different database
operations. At last execute query to complete your operation.
Hibernate Criteria :
Hibernate provide a high object oriented concept of criteria. Criteria
objects are used to perform
database operations
under object oriented concepts.
OR
Q.5 (a) Show the use of JSP page directive tag with its attributes. 07
The page directive is used to provide instructions to the container
that pertain to the current
JSP page. You may code page directives anywhere in your JSP
page. By convention, page
directives are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
You can write XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value" />
Attributes:
Following is the list of attributes associated with page directive:
Attribute Purpose
buffer Specifies a buffering model for the output stream.
autoFlush Controls the behavior of the servlet output buffer.
contentType Defines the character encoding scheme.
errorPage Defines the URL of another JSP that reports on Java
unchecked
runtime exceptions.
isErrorPage Indicates if this JSP page is a URL specified by another
JSP
page's errorPage attribute.
extends Specifies a superclass that the generated servlet must
extend
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-63
import Specifies a list of packages or classes for use in the JSP as
the
Java import statement does for Java classes.
info Defines a string that can be accessed with the servlet's
getServletInfo() method.
isThreadSafe Defines the threading model for the generated servlet.
language Defines the programming language used in the JSP page.
session Specifies whether or not the JSP page participates in HTTP
sessions
isELIgnored Specifies whether or not EL expression within the JSP
page will
be ignored.
isScriptingEnabled Determines if scripting elements are allowed for
use.
The buffer Attribute:
The buffer attribute specifies buffering characteristics for the server
output response object.
You may code a value of "none" to specify no buffering so that all
servlet output is immediately
directed to the response object or you may code a maximum buffer
size in kilobytes, which
directs the servlet to write to the buffer before writing to the response
object.
To direct the servlet to write output directly to the response output
object, use the following:
<%@ page buffer="none" %>
Use the following to direct the servlet to write output to a buffer of
size not less than 8 kilobytes:
<%@ page buffer="8kb" %>
The autoFlush Attribute:
The autoFlush attribute specifies whether buffered output should be
flushed automatically when
the buffer is filled, or whether an exception should be raised to
indicate buffer overflow.
A value of true (default) indicates automatic buffer flushing and a
value of false throws an
exception.
The following directive causes the servlet to throw an exception when
the servlet's output buffer
is full:
<%@ page autoFlush="false" %>
This directive causes the servlet to flush the output buffer when full:
<%@ page autoFlush="true" %>
Usually, the buffer and autoFlush attributes are coded on a single
page directive as follows:
<%@ page buffer="16kb" autoflush="true" %>
The contentType Attribute:
The contentType attribute sets the character encoding for the JSP
page and for the generated
response page. The default content type is text/html, which is the
standard content type for
HTML pages.
If you want to write out XML from your JSP, use the following page
directive:
<%@ page contentType="text/xml" %>
The following statement directs the browser to render the generated
page as HTML:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-64
<%@ page contentType="text/html" %>
The following directive sets the content type as a Microsoft Word
document:
<%@ page contentType="application/msword" %>
You can also specify the character encoding for the response. For
example, if you wanted to
specify that the resulting page that is returned to the browser uses
ISO Latin 1, you would use
the following page directive:
<%@ page contentType="text/html:charset=ISO-8859-1" %>
The errorPage Attribute:
The errorPage attribute tells the JSP engine which page to display if
there is an error while the
current page runs. The value of the errorPage attribute is a relative
URL.
The following directive displays MyErrorPage.jsp when all uncaught
exceptions are thrown:
<%@ page errorPage="MyErrorPage.jsp" %>
The isErrorPage Attribute:
The isErrorPage attribute indicates that the current JSP can be used
as the error page for
another JSP.
The value of isErrorPage is either true or false. The default value of
the isErrorPage attribute is
false.
For example, the handleError.jsp sets the isErrorPage option to true
because it is supposed to
handle errors:
<%@ page isErrorPage="true" %>
The extends Attribute:
The extends attribute specifies a superclass that the generated
servlet must extend.
For example, the following directive directs the JSP translator to
generate the servlet such that
the servlet extends somePackage.SomeClass:
<%@ page extends="somePackage.SomeClass" %>
The import Attribute:
The import attribute serves the same function as, and behaves like,
the Java import statement.
The value for the import option is the name of the package you want
to import.
To import java.sql.*, use the following page directive:
<%@ page import="java.sql.*" %>
To import multiple packages you can specify them separated by
comma as follows:
<%@ page import="java.sql.*,java.util.*" %>
By default, a container automatically imports java.lang.*,
javax.servlet.*, javax.servlet.jsp.*, and
javax.servlet.http.*.
The info Attribute:
The info attribute lets you provide a description of the JSP. The
following is a coding example:
<%@ page info="This JSP Page Written By ZARA" %>
The isThreadSafe Attribute:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-65
The isThreadSafe option marks a page as being thread-safe. By
default, all JSPs are
considered thread-safe. If you set the isThreadSafe option to false,
the JSP engine makes sure
that only one thread at a time is executing your JSP.
The following page directive sets the isThreadSafe option to false:
<%@ page isThreadSafe="false" %>
The language Attribute:
The language attribute indicates the programming language used in
scripting the JSP page.
For example, because you usually use Java as the scripting
language, your language option
looks like this:
<%@ page language="java" %>
The session Attribute:
The session attribute indicates whether or not the JSP page uses
HTTP sessions. A value of
true means that the JSP page has access to a builtin session object
and a value of false means
that the JSP page cannot access the builtin session object.
Following directive allows the JSP page to use any of the builtin
object session methods such
as session.getCreationTime() or session.getLastAccessTime():
<%@ page session="true" %>
The isELIgnored Attribute:
The isELIgnored option gives you the ability to disable the evaluation
of Expression Language
(EL) expressions which has been introduced in JSP 2.0
The default value of the attribute is true, meaning that expressions,
${...}, are evaluated as
dictated by the JSP specification. If the attribute is set to false, then
expressions are not
evaluated but rather treated as static text.
Following directive set an expressions not to be evaluated:
<%@ page isELIgnored="false" %>
The isScriptingEnabled Attribute:
The isScriptingEnabled attribute determines if scripting elements are
allowed for use.
The default value (true) enables scriptlets, expressions, and
declarations. If the attribute's value
is set to false, a translation-time error will be raised if the JSP uses
any scriptlets, expressions
(non-EL), or declarations.
(b) How can you implement OR Mapping in Hibernate? Give an
example. 07
It's good to understand the need for object/relational mapping (ORM)
in Java applications, but
you're probably eager to see Hibernate in action. We'll start by
showing you a simple example
that demonstrates some of its power.
As you're probably aware, it's traditional for a programming book to
start with a "Hello World"
example. In this chapter, we follow that tradition by introducing
Hibernate with a relatively
simple "Hello World" program. However, simply printing a message
to a console window won't
be enough to really demonstrate Hibernate. Instead, our program will
store newly created
objects in the database, update them, and perform queries to retrieve
them from the database.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-66
ublic class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Table Schema Relevant to this:-
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Based on the two above entities we can define following mapping file
which instructs
Hibernate how to map the defined class or classes to the database
tables.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-67
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Advance Java Technology
Term: WINTER 2011 Subject code: 170703 Date: 24/11/2011
Question Paper
Q.1 (a) Give significance of MVC architecture in building n-tier
application. Explain in detail.
07
(b) Explain various types of JDBC drivers and comment on selection
of driver. 07
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-68
Q.2 (a) Explain architecture of J2EE. List out java technologies
supported by J2EE along with
their applications. 07
(b) Explain the use of CallableStatement and PreparedStatement
with example. 07
OR
(b) What is JNDI? How can it be used for accessing various directory
services such as
LDAP, NIS, DNS? 07
Q.3 (a) How do RMI clients contact remote RMI servers? Explain
with detailed architecture of
RMI. 07
(b) Consider ableable with attributes AccountNo,CustomerName,
Balance, Phone and
Address. Write a database application which allows insertion,
updation and
deletion of records in Bank table. Print values of all customers whose
balance is greater
than 20,000. 07
OR
Q.3 (a) Write an RMI application where client sends empno and
server returns corresponding
salary by querying database. 07
(b) Write a program to demonstrate use of Internationalization for
various language. 07
Q.4 (a) Discuss Servlet life cycle methods. Explain role of web
container. 07
(b) Write a client program to send any string from its standard input
to the server
program. The server program reads the string, finds number of
characters and digits
and sends it back to client program. Use connection-oriented or
connection-less
communication. 07
OR
Q.4 (a) Explain Socket, ServerSocket, InetAddress classes. Write a
java program to find an IP
address of the machine on which the program runs. 07
(b) Develop any Servlet application which demonstrates use of
session management. 07
Q.5 (a) List and explain various swing layouts and components with
examples. 07
(b) Explain JSP tag library with examples. 07
OR
Q.5 (a) Explain object serialization in detail with example. 07
(b) What are the differences between Java Bean and basic java
SOLUTION
Q.1 (a) Give significance of MVC architecture in building n-tier
application. Explain in
detail.
Solution:
Model View Controller or MVC as it is popularly called, is a software
design pattern for
developing web applications. A Model View Controller pattern is
made up of the following
three parts:
● Model - The lowest level of the pattern which is responsible for
maintaining data.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-69
● View - This is responsible for displaying all or a portion of the data
to the user.
● Controller - Software Code that controls the interactions between
the Model and
View.
MVC is popular as it isolates the application logic from the user
interface layer and supports
separation of concerns. Here the Controller receives all requests for
the application and then
works with the Model to prepare any data needed by the View. The
View then uses the data
prepared by the Controller to generate a final presentable response.
The MVC abstraction can
be graphically represented as follows.
The model
The model is responsible for managing the data of the application. It
responds to the request
from the view and it also responds to instructions from the controller
to update itself.
The view
A presentation of data in a particular format, triggered by a
controller's decision to present
the data. They are script based templating systems like JSP, ASP,
PHP and very easy to
integrate with AJAX technology.
The controller
The controller is responsible for responding to user input and perform
interactions on the data
model objects. The controller receives the input, it validates the input
and then performs the
business operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us
see how we can use the
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-70
MVC methodology within Struts2.
(b) Explain various types of JDBC drivers and comment on selection
of driver. 07
Solution:
A JDBC application is composed of multiple layers, as shown in
Figure
JDBC architecture
The topmost layer in this model is the Java application. Java
applications are portable?
you can run a Java application without modification on any system
that has a Java runtime
environment installed. A Java application that uses JDBC can talk to
many databases with
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-71
few, if any, modifications. Like ODBC, JDBC provides a consistent
way to connect to a
database, execute commands, and retrieve the results. Also like
ODBC, JDBC does not
enforce a common command language?you can use Oracle-specific
syntax when connected
to an Oracle server and PostgreSQL-specific syntax when connected
to a PostgreSQL server.
If you stick to a common subset, you can achieve remarkable
portability for your applications.
The JDBC DriverManager
The JDBC DriverManager class is responsible for locating a JDBC
driver needed by the
application. When a client application requests a database
connection, the request is
expressed in the form of a URL (Uniform Resource Locator). A
typical URL might look like
jdbc:postgresql:movies.
The JDBC Driver
As each driver is loaded into a Java Virtual Machine (VM), it registers
itself with the JDBC
DriverManager. When an application requests a connection, the
DriverManager asks each
Driver whether it can connect to the database specified in the given
URL. As soon as it finds
an appropriate Driver, the search stops and the Driver attempts to
make a connection to
the database. If the connection attempt fails, the Driver will throw a
SQLException to the
application. If the connection completes successfully, the Driver
creates a Connection object
and returns it to the application.
The JDBC 2.0 architecture introduced another method for
establishing database connections:
the Data Source. A Data Source is a named collection of connection
properties that can be
used to load a Driver and create a Connection. I do not discuss the
DataSource class in
this chapter because it is not yet part of the J2SE (Java 2 Standard
Edition) standard; the
DataSource class is a component of J2EE (Java 2 Enterprise
Edition). The PostgreSQL JDBC
driver does support the DataSource class.
The JDBC-Compliant Database
The bottom layer of the JDBC model is the database. The
PostgreSQL Driver class (and
other JDBC classes) translates application commands into
PostgreSQL network requests and
translates the results back into JDBC object form.
(b) Explain the use of CallableStatement and PreparedStatement
with example. 07
Solution:
Just as a Connection object creates the Statement and
PreparedStatement objects, it
also creates the CallableStatement object which would be used to
execute a call to a
database stored procedure.
Callable Statement with Example:-
Creating CallableStatement Object to Create and Call Stored
Procedure:
Suppose, you need to execute the following Oracle stored procedure:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-72
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The
PreparedStatement object
only uses the IN parameter. The CallableStatement object can use
all three.
Here are the definitions of each:
Parameter Description
IN A parameter whose value is unknown when the SQL
statement is created. You bind values to IN parameters with
the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement
it returns. You retrieve values from theOUT parameters with
the getXXX() methods.
INOUT A parameter that provides both input and output values.
You bind variables with the setXXX() methods and retrieve
values with the getXXX() methods.
The following code snippet shows how to employ the
Connection.prepareCall() method
to instantiate a CallableStatement object based on the preceding
stored procedure:
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}finally { . . .
}
:: Prepared Statements:-
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-73
PreparedStatement interface ofjava.sql package twice in a program.
According to our
requirement we can use the PreparedStatement object.
ThePreparedStatement object
represents the precompiled SQL statement. Whenever, the SQL
statement is precompiled
then it stored in the PreparedStatement object which executes the
statement many times
and it reduces the time duration of execution. The
PreparedStatement uses the '?' with
SQL statement that provides the facility for setting an appropriate
conditions in it. See brief
description below:
Description of program:
In this program we are going to retrieve the movies name and it
releases year from
the 'movies' database table which releases in the year 2002 and
2003 by using the
PreparedStatement object. For this to work, first of all we will
establish the connection with
MySQL database by using the JDBC driver. When the connection
has been established then
we will pass the SQL statement with some conditions in the
prepareStatement method that
returns the PreparedStatement object, after this only we will get the
result according to our
requirements. If any problem arises in this then it will display a
message "SQL statement is
not executed!".
Here is the code program:
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-74
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-75
}
}
}
OR
(b) What is JNDI? How can it be used for accessing various directory
services such as LDAP, NIS, DNS? 07
Solution:
Naming Service? Is a service which allows us to store and retrieve
simple
objects with a unique name. It is just like one of the storage unit.
Directory Service? Is an added service on top of naming service
which allows
us to store and retrieve objects with some directory names (i.e,
maintained into
groups)
These services are implemented by different vendors where each
vendor
provides their own APIs and protocols to interact with theirs naming
and
directory services.
If any java application wants to use these services, it has to plugin to
any of the
vendor provided implementation, then
● Application becomes vendor specific
● While deploying we need to know about the vendor and its service
API
● While migrating the application from one vendor to another we
need to
change the code base of the application
To avoid these problems we want a standard abstraction through
which a java
application can interact with any vendor implemented Naming and
Directory
Service. To meet the above requirement SUN has released standard
API
providing solution to the above mentioned problems. These
standards have
been released under JNDI (Java Naming and Directory Service)
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-76
JNDI is an standard abstraction which allows any java application to
interact
with any vendor implemented naming and Directory Service.
In this case if java application wants to interact with any naming
registry it
just requires to prepare a request in JNDI format using JNDI API i.e,
request
is explained and submitted to JNDI API classes where JNDI API
uses the
information given by the java application and locates the SPI
implementation
and initializes it.
JNDI API dispatches the request to the SPI implementation through
JNDI SPI.
SPI implementation converts the request and interact with the
respective
registry to process the request, collects the response convert it into
the JNDI
format and return it.
JNDI API returns response to the java application.
:: DNS:-
Mapping DNS Content to JNDI
The DNS service provider maps DNS names, nodes, and resource
records
onto JNDI data types as follows.
Names
DNS domain names are represented by JNDI compound
Nameobjects with
right-to-left, dot-separated syntax, and with backslash (\) as the
escape
character. Escape sequences of the form \DDDmay also be used,
where DDDis
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-77
a three-digit decimal value. Names are case-insensitive. A fully-
qualified name
ending with an explicit root domain label (".") is represented by a
compound
Nameobject with an empty component in the most-significant
position.
Host names are a subset of domain names. Their labels contain only
US-ASCII
letters, digits, and hyphens, and none may begin or end with a
hyphen. While
names not conforming to these rules may be valid domain names,
they will
not be usable by a number of DNS applications, and should in most
cases be
avoided.
DNS does not specify an encoding (such as UTF-8) to use for
characters other
than those of US-ASCII. As a consequence, no character in a DNS
name will
ever have a non-zero high-order byte. When work on
internationalizing domain
names is finalized, the DNS service provider may be updated to
conform to that
work.
Nodes and Resource Records
A DNS node is represented by a DirContextobject. The resource
records of
the node are represented by attributes of the context. For example, if
the DNS
node example.com contains an A record with the address 192.0.2.33
and an
MX record with the data "10 example.com", the corresponding JNDI
context
will have an attribute with identifier "A" and string value "192.0.2.33"
and an
attribute with identifier "MX" and string value "10 example.com".
Multiple records of the same type are represented as multi-valued
attributes.
Records of unsupported types are represented by attributes with
numeric
identifiers and with byte arrays as values.
Attribute Identifiers
DNS resource record class and type names are mapped onto JNDI
attribute
identifiers. If a record is in the internet class, the corresponding
attribute ID is
simply the record's type name. If the type is an unsupported one, its
integer
value is used instead. If the record is not in the internet class, the
class name
(or integer class value) is prepended to the attribute ID, separated by
a space.
For example, the attribute identifier "AAAA" represents an IPv6
address record,
and the attribute identifier "HS 97" represents a resource record of
type 97 in
the Hesiod class.
Superclass attribute identifiers are also defined. These may be useful
when
querying records using the DirContext.getAttributes() method. If an
attribute
name has "*" in place of a type name (or class name), it represents
records of
any type (or class). For example, the attribute identifier "IN *" may be
passed
to the getAttributes() method to find all internet class records. The
attribute
identifier "* *" represents records of any class or type.
::LDAP:-
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-78
The Lightweight Directory Access Protocol (LDAP), which traces its
roots to the
.500 protocol, was developed in the early 1990s as a standard
directories
protocol. LDAP defines how clients should access data on the server,
not how
that data is stored on the server. This allows LDAP to become a
frontend to any
type of data store.
LDAP's basic structure is based on a simple information tree
metaphor called a
directory information tree (DIT). Each leaf in the tree is an entry; the
first or toplevel
entry is the root entry. An entry includes a distinguished name (DN)
and
any number of attribute/value pairs. The DN, which is the name of an
entry,
must be unique. It shows the relationship between the entry and the
rest of the
DIT in a manner similar to the way in which a file's full path name
shows its
relationship with the rest of the files in a filesystem. While a path to a
file reads
left to right, a DN, in contrast, reads from right to left. Here is an
example:
uid=styagi,ou=people,o=myserver.com
Q.3 (a) How do RMI clients contact remote RMI servers? Explain
with
detailed architecture of RMI. 07
Solution:
Steps to for RMI Client to call Remote Server as below:
● The client procedure calls the client stub in the normal way.
● The client stub builds a message and traps to the kernel.
● The kernel sends the message to the remote kernel.
● The remote kernel gives the message to the server stub
● The server stub unpacks the parameters and calls the server.
● The server does the work and returns the result to the stub.
● The server stub packs it in a message and traps to the kernel.
● The remote kernel sends the message to the clients kernel.
● The clients kernel gives the message to the client stub.
● The stub unpacks the result and returns to the client.
The basic steps to write client-service application using RMI.
● Assigning the security manager and then obtaining the reference to
the
service
● Contacting the RMI registry to obtain the remote object’s reference
and
invoking its methods
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-79
● Requesting the name for the service
● Invoke the remote method.
RMI Architecture:-
Solution:
RMI’s purpose is to make objects in separate JVM’s look alike and
act like local
objects. The JVM that calls the
remote object is usually referred to as a client and the JVM that
contains the
remote object is the server.
One of the most important aspects of the RMI design is its intended
transparency. Applications do not know
whether an object is remote or local. A method invocation on the
remote object
has the same syntax as a method
invocation on a local object, though under the hood there is a lot
more going on.
• In RMI the term “Server” does not refers to a physical server or
application
but to a single remote object having methods that can be remotely
invoked.Similarly the Term “Client” does not refer to a client m/c but
actually
refers to the object invoking a remote method on a remote object.
• The same object can be both a client and a server.
Although obtaining a reference to a remote object is somewhat
different from
doing so for local objects. Once we have the reference, we use the
remote
object as if it were local. The RMI infrastructure will automatically
intercept the method call, find the remote object and process the
request
remotely. This location transparency
even includes garbage collection.
A remote object is always accessed via its remote interface. In other
words the
client invokes methods on the
object only after casting the reference to the remote interface.
The RMI implementation is essentially built from three abstraction
layers:
• The Stub/Skeleton Layer
• The Remote Reference Layer
•The Transport Layer
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-80
The following diagram shows the RMI Architecture:
The Stub/Skeleton Layer
This layer intercepts method calls made by the client to the interface
reference
and redirects these calls to a
remote object. Stubs are specific to the client side, whereas
skeletons are
found on the server side.
To achieve location transparency, RMI introduces two special kinds
of objects
known as stubs and skeletons
that serve as an interface between an application and rest of the RMI
system.
This Layer’s purpose is to transfer
data to the Remote Reference Layer via marshalling and
unmarshalling.
Marshalling refers to the process of
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-81
converting the data or object being transferred into a byte stream and
unmarshalling is the reverse - converting
the stream into an object or data. This conversion is achieved via
object
serialization.
The Stub/ Skeleton layer of the RMI lies just below the actual
application and is
based on the proxy design
pattern. In the RMI use of the proxy pattern, the stub class plays the
role of the
proxy for the remote service
implementation. The skeleton is a helper class that is generated by
RMI to help
the object communicate with the
stub; it reads the parameters for the method call from the link, makes
the call to
the remote service
implementation object, accepts the return value and then writes the
return value
back to the stub.
In short, the proxy pattern forces method calls to occur through a
proxy that
acts as a surrogate, delegating all
calls to the actual object in a manner transparent to the original
caller.
Stub
The stub is a client-side object that represents (or acts as a proxy for)
the
remote object. The stub has the same interface, or list of methods, as
the
remote object. However when the client calls a stub method, the stub
forwards
the request via the RMI infrastructure to the remote object (via the
skeleton),
which actually executes it.
Sequence of events performed by the stub:
• Initiates a connection with the remote VM containing the remote
object
• Marshals (writes and transmits) the parameters to the remote VM.
• Waits for the result of the method invocation.
• Unmarshals (reads) the return value or exception returned.
• Return the value to the caller
In the remote VM, each remote object may have a corresponding
skeleton.
Skeleton
On the server side, the skeleton object takes care of all the details of
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-82
“remoteness” so that the actual remote object does not need to worry
about
them. In other words we can pretty much code a remote object the
same
way as if it were local; the skeleton insulates the remote object from
the RMI
infrastructure.
Sequence of events performed by the skeleton:
• Unmarshals (reads) the parameters for the remote method
(remember that
these were marshaled by the stub on the client side)
• Invokes the method on the actual remote object implementation.
• Marshals (writes and transmits) the result (return value or
exception) to the
caller (which is then unmarshalled by the stub)
The Remote Reference Layer
The remote reference layer defines and supports the invocation
semantics of
the RMI connection. This layer
maintains the session during the method call.
The Transport Layer
The Transport layer makes the stream-based network connections
over TCP/IP
between the JVMs, and is
responsible for setting and managing those connections. Even if two
JVMs are
running on the same physical
computer, they connect through their host computers TCP/IP network
protocol
stack. RMI uses a protocol
called JRMP (Java Remote Method Protocol) on top of TCP/IP (an
analogy is
HTTP over TCP/IP).
From the JDK 1.2 the JRMP protocol was modified to eliminate the
need for
skeletons and instead use
reflection to make connections to the remote services objects. Thus
we only
need to generate stub classes in
system implementation compatible with jdk 1.2 and above. To
generate stubs
we use the Version 1.2 option
with rmic.
The RMI transport layer is designed to make a connection between
clients and
server, even in the face of
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-83
networking obstacles. The transport layer in the current RMI
implemen
(b) Consider Bank table with attributes AccountNo,CustomerName,
Balance, Phone and Address. Write a database application which
allows insertion, updation and deletion of records in Bank table.
Print values of all customers whose balance is greater than 20,000.
Solution:
import java.sql.*;
import java.util.*;
import java.io.*;
public class CallableStatementPreparedStatement
{
public static void main(String args[]) throws Exception,IOException
{
int n=0,ch=0;
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.123
:1521:XE",
"scott","tiger");
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice : ");
System.out.println("1. Insert Data");
System.out.println("2. Delete Data");
System.out.println("3. Update Data");
if(input.hasNextInt())
n = input.nextInt();
switch(n)
{
case 1 :
String query="insert into bankTable values (?,?,?,?,?)";
System.out.print("Enter Account Number : ");
if(input.hasNextInt()){
ps.setInt(1,input.nextInt());}
System.out.print("Enter Customer Name : ");
ps.setString(2,input.next());
System.out.print("Enter Balance : ");
ps.setString(3,input.next());
System.out.print("Enter Phone : ");
ps.setString(4,input.next());
System.out.print("Enter Address : ");
ps.setString(5,input.next());
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-84
int i=ps.executeUpdate();
System.out.println(i+" Account Record Iserted!!!");
break;
case 2 :
String query="delete * from bankTable where accountNumber = ?";
System.out.print("Enter Account Number : ");
if(input.hasNextInt()){
ps.setInt(1,input.nextInt());}
int i=ps.executeUpdate();
System.out.println(i+" Account Record Inserted!!!");
break;
case 3 :
System.out.println("What u want to update?");
System.out.println("1. Name");
System.out.println("2. Phone");
System.out.println("3. Address");
if(input.hasNextInt())
ch = input.nextInt();
switch(ch)
{
case 1 :
System.out.print("Enter New Name : ");
String str = input.next();
String query="update backTable set customerName = "+cname+"
where
accountNumber = ?";
System.out.print("Enter Account Number : ");
if(input.hasNextInt()){
ps.setInt(1,input.nextInt());}
int i=ps.executeUpdate();
System.out.println(i+" Account Record Updated!!!");
break;
case 2:
System.out.print("Enter New Phone : ");
String str = input.next();
String query="update backTable set phone = "+cname+" where
accountNumber
= ?";
System.out.print("Enter Account Number : ");
if(input.hasNextInt()){
ps.setInt(1,input.nextInt());}
int i=ps.executeUpdate();
stem.out.println(i+" Account Record Updated!!!");
break;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-85
case 3:
System.out.print("Enter New
Address : ");
String str = input.next();
String query="update backTable
set address = "+cname+" where accountNumber = ?";
System.out.print("Enter Account
Number : ");
if(input.hasNextInt()){
ps.setInt(1,input.nextInt());}
int i=ps.executeUpdate();
System.out.println(i+" Account
Record Updated!!!");
break;
default:
System.out.println("Wrong
Choice");
break;
}
break;
default :
System.out.println("Wrong Choice");
break;
}
Statement st=con.createStatement();
String query = "select customerName from bankTable where
balance > 20000";
ResultSet rs = st.executeQuery(query );
if(rs.next())
{
System.out.println("Customer Name : "+rs.getString(1));
}
con.close();
}
}
OR
Q.3 (a) Write an RMI application where client sends empno and
server
returns corresponding salary by querying database. 07
Solution:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-86
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote
{
void receiveMessage(String x) throws RemoteException;
}
// RmiServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
import java.sql.*;
import java.util.*;
import java.io.*;
public class RmiServer extends
java.rmi.server.UnicastRemoteObject implements
ReceiveMessageInterface throws Exception,IOException
{
String address;
Registry registry;
public void receiveMessage(String x) throws RemoteException
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.123
:1521:XE","scott","tiger");
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-87
Statement st=con.createStatement();
String query = "select salary from employeeTable where empId =
"+x;
ResultSet rs = st.executeQuery(query );
if(rs.next())
{
System.out.println("Employee's Salary whose Emp Id = "+x+"
is : "+rs.getDouble(1));
}
con.close();
}
public RmiServer() throws RemoteException
{
try
{
address = (InetAddress.getLocalHost()).toString();
}
catch(Exception e)
{
System.out.println("Server can't get INET address.");
}
int port=3232;
System.out.println("Address = " + address + ",Port = " + port);
try
{
registry = LocateRegistry.createRegistry(port);
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-88
registry.rebind("rmiServer", this);
}
catch(RemoteException e)
{
System.out.println("Remote Exception"+ e);
}
}
static public void main(String args[])
{
try
{
RmiServer server = new RmiServer();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
// RmiClient.java
import java.rmi.*;
import java.rmi.registry.*;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-89
import java.net.*;
public class RmiClient
{
static public void main(String args[])
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String empNo=args[2];
System.out.println("Sending " + empNo + " to " + serverAddress + " :
"+
serverPort);
try
{
registry=LocateRegistry.getRegistry(serverAddress,(new
Integer(serverPort)).intValue());
rmiServer=(ReceiveMessageInterface)(registry.lookup("rmiServer"));
rmiServer.receiveMessage(empNo);
}
catch(RemoteException e)
{
e.printStackTrace();
}
catch(NotBoundException e)
{
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-90
System.err.println(e);
}
}
}
(b) Write a program to demonstrate use of Internationalization for
various language supports. 07
Solution:
import java.util.*;
import java.io.*;
public class InternationalizationLanguageSupport
{
public static void main(String s[]) throws Exception
{
String country,language;
Locale locale;
ResourceBundle rb;
int n=0;
Scanner input = new Scanner(System.in);
System.out.println("Select Your Language : ");
System.out.println("1. English");
System.out.println("2. France");
System.out.println("3. Spanish");
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-91
if(input.hasNextInt())
n = input.nextInt();
switch(n)
{
case 2 :
language = "fr";
country = "FR";
break;
case 3 :
language = "es";
country = "ES";
break;
default:
language = "en";
country = "US";
break;
}
locale = new Locale(language, country);
rb =
ResourceBundle.getBundle("InternationalizationLanguageSupports",
locale);
System.out.println(rb.getString("localeInfo") + " ( " +
locale.getDisplayLanguage() + "," + locale.getDisplayCountry() +
").\n");
System.out.println(rb.getString("welcomeUser"));
System.out.println(rb.getString("exitUser"));
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-92
}
}
Q.4 (a) Discuss Servlet life cycle methods. Role of web container. 07
Solution:
A servlet life cycle can be defined as the entire process from its
creation till the
destruction. The following are the paths followed by a servlet
● The servlet is initialized by calling the init () method.
● The servlet calls service() method to process a client's request.
● The servlet is terminated by calling the destroy() method.
● Finally, servlet is garbage collected by the garbage collector of the
JVM.
Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when
the servlet
is first created, and not called again for each user request. So, it is
used for
one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL
corresponding
to the servlet, but you can also specify that the servlet be loaded
when the
server is first started.
When a user invokes a servlet, a single instance of each servlet gets
created,
with each user request resulting in a new thread that is handed off to
doGet or
doPost as appropriate. The init() method simply creates or loads
some data that
will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}
The service() method :
The service() method is the main method to perform the actual task.
The servlet
container (i.e. web server) calls the service() method to handle
requests coming
from the client( browsers) and to write the formatted response back
to the
client.
Each time the server receives a request for a servlet, the server
spawns a new
thread and calls service. The service() method checks the HTTP
request type
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-93
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete,
etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method
invokes
doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you
have
nothing to do with service() method but you override either doGet() or
doPost()
depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in
each
service request. Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an
HTML form
that has no METHOD specified and it should be handled by doGet()
method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists
POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() method :
The destroy() method is called only once at the end of the life cycle
of a servlet.
This method gives your servlet a chance to close database
connections, halt
background threads, write cookie lists or hit counts to disk, and
perform other
such cleanup activities.
After the destroy() method is called, the servlet object is marked for
garbage
collection. The destroy method definition looks like this:
public void destroy() {
// Finalization code...
}
Architecture Digram Demonstrate the Role of Web Container:
The following figure depicts a typical servlet life-cycle scenario.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-94
● First the HTTP requests coming to the server are delegated to the
servlet container.
● The servlet container loads the servlet before invoking the service()
method.
● Then the servlet container handles multiple requests by spawning
multiple threads, each thread executing the service() method of a
single
instance of the servlet.
(b) Write a client program to send any string from its standard input
to
the server program. The server program reads the string, finds
number
of characters and digits and sends it back to client program. Use
connection-oriented or connection-less communication.07
Solution:
// Server.java
import java.io.*;
import java.net.*;
class Server
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-95
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
System.out.println("Connection established");
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
String str,str1;
while((str = br.readLine()) != null)
{
System.out.println("Counting Characters and Digits from
String...");
int countChar = 0,countNumber = 0;
for(int i=0;i<str.length();i++)
{
if( (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') || (str.charAt(i)
>= 'a' && str.charAt(i) <= 'z'))
countChar++;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-96
else if(str.charAt(i) >= '0' && str.charAt(i) <= '9')
countNumber++;
}
str1 = "Total Number Of Characters = " + countChar;
str1 += "Total Number Of Digits = " + countNumber;
ps.println(str1);
}
ps.close();
br.close();
kb.close();
ss.close();
s.close();
System.exit(0);
}
}
}
// Client.java
import java.io.*;
import java.net.*;
class Client
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-97
{
public static void main(String args[]) throws Exception
{
Socket s = new Socket("localhost", 888);
int stop = 1;
DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
String str="",str1="";
do
{
str = kb.readLine();
dos.writeBytes(str+"\n");
str1 = br.readLine();
System.out.println(str1);
}while(stop != 1);
dos.close();
br.close();
kb.close();
s.close();
}
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-98
Q.4 (a) Explain Socket, ServerSocket, InetAddress classes. Write a
java
program to find an IP address of the machine on which the
program runs. 07
Solution:
Sockets provide the communication mechanism between two
computers using
TCP. A client program creates a socket on its end of the
communication and
attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on
its end of
the communication. The client and server can now communicate by
writing to
and reading from the socket.
The java.net.Socket class represents a socket, and the
java.net.ServerSocket
class provides a mechanism for the server program to listen for
clients and
establish connections with them.
The following steps occur when establishing a TCP connection
between two
computers using sockets:
● The server instantiates a ServerSocket object, denoting which port
number communication is to occur on.
● The server invokes the accept() method of the ServerSocket class.
This
method waits until a client connects to the server on the given port.
● After the server is waiting, a client instantiates a Socket object,
specifying the server name and port number to connect to.
● The constructor of the Socket class attempts to connect the client
to
the specified server and port number. If communication is
established,
the client now has a Socket object capable of communicating with
the
server.
● On the server side, the accept() method returns a reference to a
new
socket on the server that is connected to the client's socket.
After the connections are established, communication can occur
using I/O
streams. Each socket has both an OutputStream and an
InputStream. The
client's OutputStream is connected to the server's InputStream, and
the client's
InputStream is connected to the server's OutputStream.
TCP is a twoway communication protocol, so data can be sent
across both
streams at the same time. There are following usefull classes
providing
complete set of methods to implement sockets.
ServerSocket Class Methods:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-99
The java.net.ServerSocket class is used by server applications to
obtain a port
and listen for client requests
The ServerSocket class has four constructors:
SN Methods with Description
1 public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An
exception occurs if the port is already bound by another application.
2 public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies
how
many incoming clients to store in a wait queue.
3 public ServerSocket(int port, int backlog, InetAddress address)
throws
IOException
Similar to the previous constructor, the InetAddress parameter
specifies
the local IP address to bind to. The InetAddress is used for servers
that
may have multiple IP addresses, allowing the server to specify which
of its
IP addresses to accept client requests on
4 public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use
the
bind() method when you are ready to bind the server socket
If the ServerSocket constructor does not throw an exception, it
means that your
application has successfully bound to the specified port and is ready
for client
requests.
Here are some of the common methods of the ServerSocket class:
SN Methods with Description
1 public int getLocalPort()
Returns the port that the server socket is listening on. This method is
useful
if you passed in 0 as the port number in a constructor and let the
server find
a port for you.
2 public Socket accept() throws IOException
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-100
Waits for an incoming client. This method blocks until either a client
connects to the server on the specified port or the socket times out,
assuming that the time-out value has been set using the
setSoTimeout()
method. Otherwise, this method blocks indefinitely
3 public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a
client
during the accept().
4 public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the
SocketAddress
object. Use this method if you instantiated the ServerSocket using
the noargument
constructor.
When the ServerSocket invokes accept(), the method does not return
until a
client connects. After a client does connect, the ServerSocket
creates a new
Socket on an unspecified port and returns a reference to this new
Socket. A
TCP connection now exists between the client and server, and
communication
can begin.
Socket Class Methods:
The java.net.Socket class represents the socket that both the client
and server
use to communicate with each other. The client obtains a Socket
object by
instantiating one, whereas the server obtains a Socket object from
the return
value of the accept() method.
The Socket class has five constructors that a client uses to connect
to a server:
SN Methods with Description
1 public Socket(String host, int port) throws UnknownHostException,
IOException.
This method attempts to connect to the specified server at the
specified
port. If this constructor does not throw an exception, the connection
is
successful and the client is connected to the server.
2 public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the
host is
denoted by an InetAddress object.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-101
3 public Socket(String host, int port, InetAddress localAddress, int
localPort)
throws IOException.
Connects to the specified host and port, creating a socket on the
local host
at the specified address and port.
4 public Socket(InetAddress host, int port, InetAddress localAddress,
int
localPort) throws IOException.
This method is identical to the previous constructor, except that the
host is
denoted by an InetAddress object instead of a String
5 public Socket()
Creates an unconnected socket. Use the connect() method to
connect this
socket to a server.
When the Socket constructor returns, it does not simply instantiate a
Socket
object but it actually attempts to connect to the specified server and
port.
Some methods of interest in the Socket class are listed here. Notice
that both
the client and server have a Socket object, so these methods can be
invoked
by both the client and server.
SN Methods with Description
1 public void connect(SocketAddress host, int timeout) throws
IOException
This method connects the socket to the specified host. This method
is
needed only when you instantiated the Socket using the no-argument
constructor.
2 public InetAddress getInetAddress()
This method returns the address of the other computer that this
socket is
connected to.
3 public int getPort()
Returns the port the socket is bound to on the remote machine.
4 public int getLocalPort()
Returns the port the socket is bound to on the local machine.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-102
5 public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket.
6 public InputStream getInputStream() throws IOException
Returns the input stream of the socket. The input stream is
connected to the
output stream of the remote socket.
7 public OutputStream getOutputStream() throws IOException
Returns the output stream of the socket. The output stream is
connected to
the input stream of the remote socket
8 public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable
of
connecting again to any server
InetAddress Class Methods:
This class represents an Internet Protocol (IP) address. Here are
following
usefull methods which you would need while doing socket
programming:
SN Methods with Description
1 static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
2 static InetAddress getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name and IP
address.
3 static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name.
4 String getHostAddress()
Returns the IP address string in textual presentation.
5 String getHostName()
Gets the host name for this IP address.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-103
6 static InetAddress InetAddress getLocalHost()
Returns the local host.
7 String toString()
Converts this IP address to a String.
Program to find an IP address of the machine on which the program
runs.
Solution:
import java.util.*;
import java.lang.*;
import java.net.*;
public class getIP
{
public static void main(String args[])
{
try
{
InetAddress IPAddressOfMachine =
InetAddress.getLocalHost();
System.out.println("IP of Your system is : " +
IPAddressOfMachine.getHostAddress());
}
catch (Exception e)
{
System.out.println("Exception : " + e.getMessage());
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-104
}
}
}
(b) Develop any Servlet application which demonstrates use of
session
management. 07
Solution:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime =
new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page.
if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-105
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
Q.5 (a) List and explain various swing layouts and components with
examples.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-106
Solution:
A layout manager determines the location and size of components
placed into a container.
Different layout manager classes use different algorithms for
determining size and location.
The only layout manager methods that are normally used are
constructors.
FlowLayout Class
A FlowLayout places components in rows. Each component is given
its preferred size. When
a row has as many components as can fit, a new row is started.
This is the default layout manager for JPanel. There are three useful
constructors.
● new FlowLayout()
● new FlowLayout(int algn)
● new FlowLayout(int algn, int hgap, int vgap)
BorderLayout Class
A BorderLayout divides its container into three horizontal stripes: the
top (north), the middle,
and the bottom (south). At most one component can be placed into
the north or south. These
components get their preferred height, but they take up the full width
of the container.
The middle stripe get whatever height is available after deducting the
heights of the north and
south components. It can hold three components: one on the left
(west), one in the middle
(center), and one on the right (east). The east and west components
get their preferred
widths, but they take up the full height of the middle stripe.
This is the default layout manager for content panes. There are two
useful constructors.
● new BorderLayout()
● new BorderLayout(int hgap, int vgap)
When components are added to a container that uses a
BorderLayout, they should be added
with the following kind of statement.
container.add(component, whr);
The parameter whr should be one of the following.
● BorderLayout.NORTH
● BorderLayout.EAST
● BorderLayout.SOUTH
● BorderLayout.WEST
● BorderLayout.CENTER
GridLayout Class
A GridLayout places components in a rectangular grid whose cells all
have the same size.
Each component is sized to fill the cell.
There are two useful GridLayout constructors.
● new GridLayout(int rows, int cols)
● new GridLayout(int rows, int cols, int hgap, int vgap)
BoxLayout Class
A BoxLayout places components into a single row or column, as
specified by the second
constructor parameter. For a row (parameter value
BoxLayout.X_AXIS), each component get
its preferred height. The widths are adjusted according to a formula
that incorporates both
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-107
preferred and maximum widths. For a column (parameter value
BoxLayout.Y_AXIS), each
component gets its preferred width. The heights are adjusted
according to a formula that
incorporates both preferred and maximum heights.
● new BoxLayout(Component c, BoxLayout.X_AXIS)
● new BoxLayout(Component c, BoxLayout.Y_AXIS)
The component c must be the container that is being laid out.
(b) Explain JSP tag library with examples. 07
Solution:
The JavaServer Pages Standard Tag Library (JSTL) is a collection of
useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and
conditionals, tags for
manipulating XML documents, internationalization tags, and SQL
tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into
following JSTL tag library
groups that can be used when creating a JSP page:
● Core Tags
● Formatting tags
● SQL tags
● XML tags
● JSTL Functions
Core Tags:
The core group of tags are the most frequently used JSTL tags.
Following is the syntax to
include JSTL Core library in your JSP:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:set > Sets the result of an expression evaluation in a 'scope'
<c:remove > Removes a scoped variable (from a particular scope, if
specified).
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-108
<c:catch> Catches any Throwable that occurs in its body and
optionally exposes it.
<c:if> Simple conditional tag which evalutes its body if the
supplied condition is true.
<c:choose> Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by
<when> and <otherwise>
<c:when> Subtag of <choose> that includes its body if its condition
evalutes to 'true'.
<c:otherwise > Subtag of <choose> that follows <when> tags and
runs
only if all of the prior conditions evaluated to 'false'.
<c:import> Retrieves an absolute or relative URL and exposes its
contents to either the page, a String in 'var', or a Reader
in 'varReader'.
<c:forEach > The basic iteration tag, accepting many different
collection
types and supporting subsetting and other functionality .
<c:forTokens> Iterates over tokens, separated by the supplied
delimeters.
<c:param> Adds a parameter to a containing 'import' tag's URL.
<c:redirect > Redirects to a new URL.
<c:url> Creates a URL with optional query parameters
Formatting tags:
The JSTL formatting tags are used to format and display text, the
date, the time, and numbers
for internationalized Web sites. Following is the syntax to include
Formatting library in your
JSP:
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the list of Formatting JSTL Tags:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-109
Tag Description
<fmt:formatNumber> To render numerical value with specific
precision or
format.
<fmt:parseNumber> Parses the string representation of a number,
currency, or
percentage.
<fmt:formatDate> Formats a date and/or time using the supplied
styles and
pattern
<fmt:parseDate> Parses the string representation of a date and/or
time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration
variable.
<fmt:setBundle> Loads a resource bundle and stores it in the named
scoped variable or the bundle configuration variable.
<fmt:timeZone> Specifies the time zone for any time formatting or
parsing
actions nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone
configuration
variable
<fmt:message> To display an internationalized message.
<fmt:requestEncoding> Sets the request character encoding
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational
databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-110
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for
prototyping
<sql:query> Executes the SQL query defined in its body or through
the
sql attribute.
<sql:update> Executes the SQL update defined in its body or through
the sql attribute.
<sql:param> Sets a parameter in an SQL statement to the specified
value.
<sql:dateParam> Sets a parameter in an SQL statement to the
specified
java.util.Date value.
<sql:transaction > Provides nested database action elements with a
shared
Connection, set up to execute all statements as one
transaction.
XML tags:
The JSTL XML tags provide a JSP-centric way of creating and
manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML
data. This includes
parsing XML, transforming XML data, and flow control based on
XPath expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy
following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib:
● XercesImpl.jar: Download it from
http://www.apache.org/dist/xerces/j/
● xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html
Following is the list of XML JSTL Tags:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-111
<x:parse> Use to parse XML data specified either via an attribute or
in the tag body.
<x:set > Sets a variable to the value of an XPath expression.
<x:if > Evaluates a test XPath expression and if it is true, it
processes its body. If the test condition is false, the body
is ignored.
<x:forEach> To loop over nodes in an XML document.
<x:choose> Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by
<when> and <otherwise>
<x:when > Subtag of <choose> that includes its body if its expression
evalutes to 'true'
<x:otherwise > Subtag of <choose> that follows <when> tags and
runs
only if all of the prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
<x:param > Use along with the transform tag to set a parameter in
the
XSLT stylesheet
JSTL Functions:
JSTL includes a number of standard functions, most of which are
common string manipulation
functions. Following is the syntax to include JSTL Functions library in
your JSP:
<%@ taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
Following is the list of JSTL Functions:
Function Description
fn:contains() Tests if an input string contains the specified substring.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-112
fn:containsIgnoreCase() Tests if an input string contains the specified
substring
in a case insensitive way.
fn:endsWith() Tests if an input string ends with the specified suffix.
fn:escapeXml() Escapes characters that could be interpreted as XML
markup.
fn:indexOf() Returns the index withing a string of the first occurrence
of a specified substring.
fn:join() Joins all elements of an array into a string.
fn:length() Returns the number of items in a collection, or the
number of characters in a string.
fn:replace() Returns a string resulting from replacing in an input
string all occurrences with a given string.
fn:split() Splits a string into an array of substrings.
fn:startsWith() Tests if an input string starts with the specified prefix.
fn:substring() Returns a subset of a string.
fn:substringAfter() Returns a subset of a string following a specific
substring.
fn:substringBefore() Returns a subset of a string before a specific
substring.
fn:toLowerCase() Converts all of the characters of a string to lower
case.
fn:toUpperCase() Converts all of the characters of a string to upper
case.
fn:trim() Removes white spaces from both ends of a string.
Q.5 (a) Explain object serialization in detail with example. 07
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-113
Solution:
The ObjectOutputStream class is used to serialize an Object. The
following SerializeDemo
program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is
created. The program
does not generate any output, but study the code and try to
determine what the program is
doing.
Note: When serializing an object to a file, the standard convention in
Java is to give the file
a .serextension.
import java.io.*;
public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
(b) What are the differences between Java Bean and basic java
class? Explain Java
Bean Architecture. 07
Solution:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-114
::Diffrence :-
1)The java beans are serializable while class is not.
2)The bean need to follow certain conventions while class doesn't
need any convention.
3)Java bean contains only setters and getters while in class, you can
define constructor with
arguments, methods etc.
4)A class contains a main method while a bean does not.
Java Bean Architrecture:-
JavaBeans is an architecture for both using and building components
in Java. This
architecture supports the features of software reuse, component
models, and object
orientation. One of the most important features of JavaBeans is that
it does not alter the
existing Java language. If you know how to write software in Java,
you know how to use and
create Beans. The strengths of Java are built upon and extended to
create the JavaBeans
component architecture.
Although Beans are intended to work in a visual application
development tool, they don't
necessarily have a visual representation at run-time (although many
will). What this does
mean is that Beans must allow their property values to be changed
through some type of
visual interface, and their methods and events should be exposed so
that the development
tool can write code capable of manipulating the component when the
application is executed.
Creating a Bean doesn't require any advanced concepts. So before I
go any further, here is
some code that implements a simple Bean:
public class MyBean implements java.io.Serializable
{
protected int theValue;
public MyBean()
{
}
public void setMyValue(int newValue)
{
theValue = newValue;
}
public int getMyValue()
{
return theValue;
}
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-115
Advance Java Technology
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-116
Term: SUMMER 2013 Subject code: 170703 Date: 28/05/2013
Q.1 (a) What do you mean by MVC architecture? Explain its role in
modern
applications and list its advantages. 07
Solution:
Model View Controller or MVC as it is popularly called, is a software
design pattern for
developing web applications. A Model View Controller pattern is
made up of the following
three parts:
● Model - The lowest level of the pattern which is responsible for
maintaining data.
● View - This is responsible for displaying all or a portion of the data
to the user.
● Controller - Software Code that controls the interactions between
the Model and
View.
MVC is popular as it isolates the application logic from the user
interface layer and supports
separation of concerns. Here the Controller receives all requests for
the application and then
works with the Model to prepare any data needed by the View. The
View then uses the data
prepared by the Controller to generate a final presentable response.
The MVC abstraction can
be graphically represented as follows.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-117
The model
The model is responsible for managing the data of the application. It
responds to the request
from the view and it also responds to instructions from the controller
to update itself.
The view
A presentation of data in a particular format, triggered by a
controller's decision to present
the data. They are script based templating systems like JSP, ASP,
PHP and very easy to
integrate with AJAX technology.
The controller
The controller is responsible for responding to user input and perform
interactions on the data
model objects. The controller receives the input, it validates the input
and then performs the
business operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us
see how we can use the
MVC methodology within Struts2.
(b) Explain the use of the PreparedStatement object of the JDBC
with an appropriate
example. 07
Solution:
PreparedStatement interface ofjava.sql package twice in a program.
According to our
requirement we can use the PreparedStatement object.
ThePreparedStatement object
represents the precompiled SQL statement. Whenever, the SQL
statement is precompiled
then it stored in the PreparedStatement object which executes the
statement many times
and it reduces the time duration of execution. The
PreparedStatement uses the '?' with
SQL statement that provides the facility for setting an appropriate
conditions in it. See brief
description below:
Description of program:
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-118
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-119
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Q.2 (a) Answer the following questions.
1. Compare the AWT and Swing.
2. Explain the JDBC URL with appropriate examples. 07
::Compare the AWT and Swing:-
There are, of course, both pros and cons to using either set of
components from the JFC in
your Java applications. Here is a summary:
AWT:
Pros
● Speed: use of native peers speeds component performance.
● Applet Portability: most Web browsers support AWT classes so
AWT applets can run
without the Java plugin.
● Look and Feel: AWT components more closely reflect the look and
feel of the OS they
run on.
Cons
● Portability: use of native peers creates platform specific limitations.
Some components
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-120
may not function at all on some platforms.
● Third Party Development: the majority of component makers,
including Borland and
Sun, base new component development on Swing components.
There is a much
smaller set of AWT components available, thus placing the burden
on the programmer
to create his or her own AWT-based components.
● Features: AWT components do not support features like icons and
tool-tips.
Swing:
Pros
● Portability: Pure Java design provides for fewer platform specific
limitations.
● Behavior: Pure Java design allows for a greater range of behavior
for Swing
components since they are not limited by the native peers that AWT
uses.
● Features: Swing supports a wider range of features like icons and
pop-up tool-tips for
components.
● Vendor Support: Swing development is more active. Sun puts
much more energy into
making Swing robust.
● Look and Feel: The pluggable look and feel lets you design a
single set of GUI
components that can automatically have the look and feel of any OS
platform
(Microsoft Windows, Solaris, Macintosh, etc.). It also makes it easier
to make global
changes to your Java programs that provide greater accessibility (like
picking a hicontrast
color scheme or changing all the fonts in all dialogs, etc.).
Cons
● Applet Portability: Most Web browsers do not include the Swing
classes, so the Java
plugin must be used.
● Performance: Swing components are generally slower and buggier
than AWT, due
to both the fact that they are pure Java and to video issues on
various platforms.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-121
Since Swing components handle their own painting (rather than
using native API's like
DirectX on Windows) you may run into graphical glitches.
● Look and Feel: Even when Swing components are set to use the
look and feel of the
OS they are run on, they may not look like their native counterparts.
::JDBC URL with appropriate examples:-
After you've loaded the driver, you can establish a connection using
theDriverManager.getConnection() method. For easy reference, let
me list the three
overloaded DriverManager.getConnection() methods:
● getConnection(String url)
● getConnection(String url, Properties prop)
● getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an
address that points to your
database.
Formulating a database URL is where most of the problems
associated with establishing a
connection occur.
Following table lists down popular JDBC driver names and database
URL.
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/
databaseName
ORACLE oracle.jdbc.driver.Oracl
eDriver
jdbc:oracle:thin:@hostname:port
Number:databaseName
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-122
DB2 COM.ibm.db2.jdbc.net.
DB2Driver
jdbc:db2:hostname:port Number/
databaseName
Sybase com.sybase.jdbc.SybDr
iver
jdbc:sybase:Tds:hostname: port Number/
databaseName
All the highlighted part in URL format is static and you need to
change only remaining part as
per your database setup.
(b) Write an RMI program to echo the message send by the client to
the
RMI server object. 07
Client Code:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements
Hello
{
public HelloImpl() throws RemoteException {}
public String sayHello() { return "Hello world!"; }
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-123
public static void main(String args[])
{
try
{
HelloImpl obj = new HelloImpl();
// Bind this object instance to the name "HelloServer"
Naming.rebind("HelloServer", obj);
}
catch (Exception e)
{
System.out.println("HelloImpl err: " + e.getMessage());
e.printStackTrace();
}
}
}
Server Code:
import java.rmi.RMISecurityManager;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class HelloClient
{
public static void main(String arg[])
{
String message = "blank";
// I download server's stubs ==> must set a SecurityManager
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-124
System.setSecurityManager(new RMISecurityManager());
try
{
Hello obj = (Hello) Naming.lookup( "//" +
"lysander.cs.ucsb.edu" +
"/HelloServer"); //objectname in registry
System.out.println(obj.sayHello());
}
catch (Exception e)
{
System.out.println("HelloClient exception: " + e.getMessage());
e.printStackTrace();
}
}
}
OR
(b) Write a client-server program using TCP sockets to echo the
messaeg send by the
client. 07
Client Code:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-125
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 10007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-126
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
Server Code:
import java.net.*;
import java.io.*;
public class EchoServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10007);
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-127
catch (IOException e)
{
System.err.println("Could not listen on port: 10007.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Q.3 (a) Describe the following.
1. Remote reference layer in RMI architecture.
2. Use of the URL class. 07
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-128
:: RMI Architrecture:-
RMI’s purpose is to make objects in separate JVM’s look alike and
act like local objects. The
JVM that calls the
remote object is usually referred to as a client and the JVM that
contains the remote object is
the server.
One of the most important aspects of the RMI design is its intended
transparency.
Applications do not know
whether an object is remote or local. A method invocation on the
remote object has the same
syntax as a method
invocation on a local object, though under the hood there is a lot
more going on.
• In RMI the term “Server” does not refers to a physical server or
application but to a single
remote object having methods that can be remotely invoked.Similarly
the Term “Client” does
not refer to a client m/c but actually refers to the object invoking a
remote method on a
remote object.
• The same object can be both a client and a server.
Although obtaining a reference to a remote object is somewhat
different from doing so for
local objects. Once we have the reference, we use the remote object
as if it were local. The
RMI infrastructure will automatically
intercept the method call, find the remote object and process the
request remotely. This
location transparency
even includes garbage collection.
A remote object is always accessed via its remote interface. In other
words the client invokes
methods on the
object only after casting the reference to the remote interface.
The RMI implementation is essentially built from three abstraction
layers:
• The Stub/Skeleton Layer
• The Remote Reference Layer
•The Transport Layer
The following diagram shows the RMI Architecture:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-129
The Stub/Skeleton Layer
This layer intercepts method calls made by the client to the interface
reference and redirects
these calls to a
remote object. Stubs are specific to the client side, whereas
skeletons are found on the server
side.
To achieve location transparency, RMI introduces two special kinds
of objects known as stubs
and skeletons
that serve as an interface between an application and rest of the RMI
system. This Layer’s
purpose is to transfer
data to the Remote Reference Layer via marshalling and
unmarshalling. Marshalling refers to
the process of
converting the data or object being transferred into a byte stream and
unmarshalling is the
reverse - converting
the stream into an object or data. This conversion is achieved via
object serialization.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-130
The Stub/ Skeleton layer of the RMI lies just below the actual
application and is based on the
proxy design
pattern. In the RMI use of the proxy pattern, the stub class plays the
role of the proxy for the
remote service
implementation. The skeleton is a helper class that is generated by
RMI to help the object
communicate with the
stub; it reads the parameters for the method call from the link, makes
the call to the remote
service
implementation object, accepts the return value and then writes the
return value back to the
stub.
In short, the proxy pattern forces method calls to occur through a
proxy that acts as a
surrogate, delegating all
calls to the actual object in a manner transparent to the original
caller.
Stub
The stub is a client-side object that represents (or acts as a proxy for)
the remote object. The
stub has the same interface, or list of methods, as the remote object.
However when the client
calls a stub method, the stub forwards the request via the RMI
infrastructure to the remote
object (via the skeleton), which actually executes it.
Sequence of events performed by the stub:
• Initiates a connection with the remote VM containing the remote
object
• Marshals (writes and transmits) the parameters to the remote VM.
• Waits for the result of the method invocation.
• Unmarshals (reads) the return value or exception returned.
• Return the value to the caller
In the remote VM, each remote object may have a corresponding
skeleton.
Skeleton
On the server side, the skeleton object takes care of all the details of
“remoteness” so that the
actual remote object does not need to worry about them. In other
words we can pretty much
code a remote object the same way as if it were local; the skeleton
insulates the remote object
from the RMI infrastructure.
Sequence of events performed by the skeleton:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-131
• Unmarshals (reads) the parameters for the remote method
(remember that
these were marshaled by the stub on the client side)
• Invokes the method on the actual remote object implementation.
• Marshals (writes and transmits) the result (return value or
exception) to the
caller (which is then unmarshalled by the stub)
The Remote Reference Layer
The remote reference layer defines and supports the invocation
semantics of the RMI
connection. This layer
maintains the session during the method call.
The Transport Layer
The Transport layer makes the stream-based network connections
over TCP/IP between the
JVMs, and is
responsible for setting and managing those connections. Even if two
JVMs are running on the
same physical
computer, they connect through their host computers TCP/IP network
protocol stack. RMI
uses a protocol
called JRMP (Java Remote Method Protocol) on top of TCP/IP (an
analogy is HTTP over
TCP/IP).
From the JDK 1.2 the JRMP protocol was modified to eliminate the
need for skeletons and
instead use
reflection to make connections to the remote services objects. Thus
we only need to generate
stub classes in
system implementation compatible with jdk 1.2 and above. To
generate stubs we use the
Version 1.2 option
with rmic.
The RMI transport layer is designed to make a connection between
clients and server, even in
the face of
networking obstacles. The transport layer in the current RMI
implemen
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-132
::URL Class:-
URL Class Methods:
The java.net.URL class represents a URL and has complete set of
methods to manipulate
URL in Java.
The URL class has several constructors for creating URLs, including
the following:
S
N
Methods with Description
1 public URL(String protocol, String host, int port, String file) throws
MalformedURLException.
Creates a URL by putting together the given parts.
2 public URL(String protocol, String host, String file) throws
MalformedURLException
Identical to the previous constructor, except that the default port for
the given
protocol is used.
3 public URL(String url) throws MalformedURLException
Creates a URL from the given String
4 public URL(URL context, String url) throws
MalformedURLException
Creates a URL by parsing the together the URL and String
arguments
The URL class contains many methods for accessing the various
parts of the URL being
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-133
represented. Some of the methods in the URL class include the
following:
S
N
Methods with Description
1 public String getPath()
Returns the path of the URL.
2 public String getQuery()
Returns the query part of the URL.
3 public String getAuthority()
Returns the authority of the URL.
4 public int getPort()
Returns the port of the URL.
5 public int getDefaultPort()
Returns the default port for the protocol of the URL.
6 public String getProtocol()
Returns the protocol of the URL.
7 public String getHost()
Returns the host of the URL.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-134
8 public String getHost()
Returns the host of the URL.
9 public String getFile()
Returns the filename of the URL.
10 public String getRef()
Returns the reference part of the URL.
11 public URLConnection openConnection() throws IOException
Opens a connection to the URL, allowing a client to communicate
with the
resource.
(b) Describe the servlet life cycle with life cycle methods. 07
Solution:
A servlet life cycle can be defined as the entire process from its
creation till the destruction.
The following are the paths followed by a servlet
● The servlet is initialized by calling the init () method.
● The servlet calls service() method to process a client's request.
● The servlet is terminated by calling the destroy() method.
● Finally, servlet is garbage collected by the garbage collector of the
JVM.
Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when
the servlet is first created,
and not called again for each user request. So, it is used for one-time
initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL
corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is
first started.
When a user invokes a servlet, a single instance of each servlet gets
created, with each user
request resulting in a new thread that is handed off to doGet or
doPost as appropriate. The
init() method simply creates or loads some data that will be used
throughout the life of the
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-135
servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}
The service() method :
The service() method is the main method to perform the actual task.
The servlet container (i.e.
web server) calls the service() method to handle requests coming
from the client( browsers)
and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and
calls service. The service() method checks the HTTP request type
(GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method
invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing
to do with service()
method but you override either doGet() or doPost() depending on
what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in
each service request.
Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an
HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists
POST as the METHOD and
it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() method :
The destroy() method is called only once at the end of the life cycle
of a servlet. This method
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-136
gives your servlet a chance to close database connections, halt
background threads, write
cookie lists or hit counts to disk, and perform other such cleanup
activities.
After the destroy() method is called, the servlet object is marked for
garbage collection. The
destroy method definition looks like this:
public void destroy() {
// Finalization code...
}
OR
Q.3 (a) Give the characteristics of the HTTP protocol and explain the
GET,HEAD and PUT methods of the HTTP protocol.
Solution:
The Hypertext Transfer Protocol (HTTP) is an application protocol for
distributed,
collaborative, hypermedia information systems.[1]HTTP is the
foundation of data
communication for the World Wide Web.
Hypertext is structured text that uses logical links (hyperlinks)
between nodes containing text.
HTTP is the protocol to exchange or transfer hypertext.
The standards development of HTTP was coordinated by the Internet
Engineering Task Force
(IETF) and the World Wide Web Consortium (W3C), culminating in
the publication of a series
of Requests for Comments (RFCs).
The GET ethod
Some other notes on GET requests:
● GET requests can be cached
● GET requests remain in the browser history
● GET requests can be bookmarked
● GET requests should never be used when dealing with sensitive
data
● GET requests have length restrictions
● GET requests should be used only to retrieve data
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-137
The POST Method
Some other notes on POST requests:
● POST requests are never cached
● POST requests do not remain in the browser history
● POST requests cannot be bookmarked
● POST requests have no restrictions on data length
HEAD Method: Same as GET but returns only HTTP headers and no
document body
(b) Give an example showing the use of EL functions. 07
Solution:
JSP Expression Language (EL) makes it possible to easily access
application data stored in
JavaBeans components. JSP EL allows you to create expressions
both (a) arithmetic and (b)
logical. Within a JSP EL expression, you can use integers, floating
point numbers, strings, the
built-in constants true and false for boolean values, and null.
Simple Syntax:
Typically, when you specify an attribute value in a JSP tag, you
simply use a string. For
example:
<jsp:setProperty name="box" property="perimeter" value="100"/>
JSP EL allows you to specify an expression for any of these attribute
values. A simple syntax
for JSP EL is as follows:
${expr}
Here expr specifies the expression itself. The most common
operators in JSP EL are . and
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-138
[]. These two operators allow you to access various attributes of Java
Beans and built-in JSP
objects.
For example above syntax <jsp:setProperty> tag can be written with
an expression like:
<jsp:setProperty name="box" property="perimeter"
value="${2*box.width+2*box.height}"/>
When the JSP compiler sees the ${} form in an attribute, it generates
code to evaluate the
expression and substitues the value of expresson.
You can also use JSP EL expressions within template text for a tag.
For example, the
<jsp:text> tag simply inserts its content within the body of a JSP. The
following <jsp:text>
declaration inserts <h1>Hello JSP!</h1> into the JSP output:
<jsp:text>
<h1>Hello JSP!</h1>
</jsp:text>
You can include a JSP EL expression in the body of a <jsp:text> tag
(or any other tag) with
the same ${} syntax you use for attributes. For example:
<jsp:text>
Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>
EL expressions can use parentheses to group subexpressions. For
example, ${(1 + 2) * 3}
equals 9, but ${1 + (2 * 3)} equals 7.
To deactivate the evaluation of EL expressions, we specify the
isELIgnored attribute of the
page directive as below:
<%@ page isELIgnored ="true|false" %>
The valid values of this attribute are true and false. If it is true, EL
expressions are ignored
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-139
when they appear in static text or tag attributes. If it is false, EL
expressions are evaluated by
the container.
Q.4 (a) Write a Web application using servlet to find the sum of all
the digits of an input
integer. 08
Solution:
Html File to get an Input:-
<html>
<body>
<form method="get" action="../TableServlet">
<table>
<tr><td>Enter a number to find its Sum:</td><td><input type="text"
name="text1"/></td></tr>
<tr><td></td><td><input type="submit" value="ok"/></td></tr>
</table>
</form>
</body>
</html>
Servlet Code:
package simpleServletExample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-140
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FactorialServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int num = Integer.parseInt(request.getParameter("text1"));
for(int i=1;i<=num;i++){
int t=t+i;
out.println(t+"<br>");
}
}
}
(b) What is XML tag library? Explain the XML core tags and show
their use. 06
Solution:
The JSTL XML tags provide a JSP-centric way of creating and
manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML
data. This includes
parsing XML, transforming XML data, and flow control based on
XPath expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-141
Before you proceed with the examples, you would need to copy
following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib:
Following is the list of XML JSTL Tags:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
<x:parse> Use to parse XML data specified either via an attribute or
in the tag body.
<x:set > Sets a variable to the value of an XPath expression.
<x:if > Evaluates a test XPath expression and if it is true, it
processes its body. If the test condition is false, the body
is ignored.
<x:forEach> To loop over nodes in an XML document.
<x:choose> Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by
<when> and <otherwise>
<x:when > Subtag of <choose> that includes its body if its expression
evalutes to 'true'
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-142
<x:otherwise > Subtag of <choose> that follows <when> tags and
runs
only if all of the prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
<x:param > Use along with the transform tag to set a parameter in
the
XSLT stylesheet
OR
Q.4 (a) Write a JSP page to display your semester mark sheet. Give
the necessary files
to deploy it. 08
Solution:
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/
html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Student Marks</title>
</head>
<body>
<h2>Student Grading System</h2>
<form action="" method="post">
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-143
<table>
<tr>
<td></td>
<td>
Select Course <select name="course">
<option value="select">select</option>
<option value="CE">CE</option>
<option value="IT">IT</option>
</select>
</td>
</tr>
</table>
<table>
<tr>
<th>Subject</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
</tr>
<tr>
<td align="center">C</td>
<td align="center"><input type="text" size="5" name="c"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">Java</td>
<td align="center"><input type="text" size="5" name="java"/></td>
<td align="center">100</td>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-144
</tr>
<tr>
<td align="center">.Net</td>
<td align="center"><input type="text" size="5" name="net"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">VB</td>
<td align="center"><input type="text" size="5" name="vb"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">DBMS</td>
<td align="center"><input type="text" size="5" name="dbms"/></td>
<td align="center">100</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr><td></td><td align="center"><input type="submit"
value="submit"/></td></tr>
</table>
</form>
<%
String c = request.getParameter("c");
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-145
String j = request.getParameter("java");
String n = request.getParameter("net");
String v = request.getParameter("vb");
String d = request.getParameter("dbms");
if(!(c == null || c.isEmpty()))
{
int cmarks = Integer.parseInt(c);
int jmarks = Integer.parseInt(j);
int nmarks = Integer.parseInt(n);
int vmarks = Integer.parseInt(v);
int dmarks = Integer.parseInt(d);
int total = cmarks+jmarks+nmarks+vmarks+dmarks;
int avg = (total)/5;
int percent = avg;
String grade ="";
if(percent < 40){
grade = "E";
//request.setAttribute("grade", grade);
}
else if(percent >= 40 && percent <=44){
grade = "D";
}
else if(percent >=45 && percent <=49){
grade = "D+";
}
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-146
else if(percent >=50 && percent <=54){
grade = "C-";
}
else if(percent >=55 && percent<=59){
grade = "C";
}
else if(percent >=60 && percent <=64){
grade = "C+";
}
else if(percent >=65 && percent<=69){
grade = "B-";
}
else if(percent >=70 && percent <=74){
grade = "B";
}
else if(percent >=75 && percent <=79){
grade = "B+";
}
else if(percent >=80 && percent <=84){
grade = "A";
}
else if (percent >=85 && percent <=100){
grade = "A+";
}
request.setAttribute("Grade", grade);
%>
<table>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-147
<tr>
<td><b>Course</b></td><td></td>
<td align="center"><%=request.getParameter("course") %>
</tr>
<tr>
<td><b>Aggregate Marks</b></td><td></td>
<td align="center"><%=total %></td>
</tr>
<tr>
<td><b>Grade</b></td><td></td>
<td align="center"><%=grade %></td>
</tr>
</table>
<%
}
%>
</body>
</html>
To deploy This file apply following steps:-
While in development I suggest creating the directory directly in the
Tomcat
/webapps directory. When it comes time for deployment, you can
package
your web application into a WAR file and go though the production
deployment
process.
The last step in creating the web application directory structure is
adding a
deployment descriptor. At this point you'll be creating a default
web.xml file that
contains only the DTD, describing the web.xml file, and an empty
<webapp/>
element. Listing 1 contains the source for a default web.xml file.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-148
Listing 1 web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
</web-app>
(b) What is doFilter() method? What are its parameters? Give its use
with proper
example. 07
Solution:
A Servlet filter is an object that can intercept HTTP requests targeted
at your web application.
A servlet filter can intercept requests both for servlets, JSP's, HTML
files or other static
content, as illustrated in the diagram below:
A Servlet Filter in a Java Web Application
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-149
In order to create a servlet filter you must implement the
javax.servlet.Filter interface. Here is
an example servlet filter implementation:
import javax.servlet.*;
import java.io.IOException;
/**
*/
public class SimpleServletFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain filterChain)
throws IOException, ServletException {
}
public void destroy() {
}
}
When the servlet filter is loaded the first time, its init() method is
called, just like with servlets.
When a HTTP request arrives at your web application which the filter
intercepts, the filter can
inspect the request URI, the request parameters and the request
headers, and based on that
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-150
decide if it wants to block or forward the request to the target servlet,
JSP etc.
It is the doFilter() method that does the interception. Here is a sample
implementation:
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain filterChain)
throws IOException, ServletException {
String myParam = request.getParameter("myParam");
if(!"blockTheRequest".equals(myParam)){
filterChain.doFilter(request, response);
}
}
Notice how the doFilter() method checks a request parameter,
myParam, to see if it equals
the string "blockTheRequest". If not, the request is forwarded to the
target of the request,
by calling thefilterChain.doFilter() method. If this method is not called,
the request is not
forwarded, but just blocked.
The servlet filter above just ignores the request if the request
parameter myParam
equals "blockTheRequest". You can also write a different response
back to the browser. Just
use the ServletResponse object to do so, just like you would inside a
servlet.
You may have to cast the ServletResponse to a HttpResponse to
obtain a PrintWriter from it.
Otherwise you only have the OutputStream available via
getOutputStream().
Here is an example:
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain filterChain)
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-151
throws IOException, ServletException {
String myParam = request.getParameter("myParam");
if(!"blockTheRequest".equals(myParam)){
filterChain.doFilter(request, response);
return;
}
HttpResponse httpResponse = (HttpResponse) httpResponse;
httpResponse.getWriter().write("a different response... e.g in HTML");
}
Configuring the Servlet Filter in web.xml
You need to configure the servlet filter in the web.xml file of your web
application, before it
works. Here is how you do that:
<filter>
<filter-name>myFilter</filter-name>
<filter-class>servlets.SimpleServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>*.simple</url-pattern>
</filter-mapping>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-152
With this configuration all requests with URL's ending in .simple will
be intercepted by the
servlet filter. All others will be left untouched.
Q.5 (a) Explain the action tags used to access the JavaBeans from a
JSP page
with example. 07
Solution:
JSP actions use constructs in XML syntax to control the behavior of
the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward
the user to another page,
or generate HTML for the Java plugin.
Common Attributes:
There are two attributes that are common to all Action elements: the
id attribute and the scope
attribute.
● Id attribute: The id attribute uniquely identifies the Action element,
and allows the
action to be referenced inside the JSP page. If the Action creates an
instance of an
object the id value can be used to reference it through the implicit
object PageContext
● Scope attribute: This attribute identifies the lifecycle of the Action
element. The id
attribute and the scope attribute are directly related, as the scope
attribute determines
the lifespan of the object associated with the id. The scope attribute
has four possible
values: (a) page, (b)request, (c)session, and (d) application.
The <jsp:include> Action
This action lets you insert files into the page being generated. The
syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP
page is translated into a
servlet, this action inserts the file at the time the page is requested.
Following is the list of attributes associated with include action:
Attribute Description
page The relative URL of the page to be included.
flush The boolean attribute determines whether the included
resource has its buffer flushed before it is included.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-153
Example:
Let us define following two files (a)date.jps and (b) main.jsp as
follows:
Following is the content of date.jsp file:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
The <jsp:useBean> Action
The useBean action is quite versatile. It first searches for an existing
object utilizing the id and
scope variables. If an object is not found, it then tries to create the
specified object.
The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="package.class" />
Once a bean class is loaded, you can use jsp:setProperty and
jsp:getProperty actions to
modify and retrieve bean properties.
Following is the list of attributes associated with useBean action:
Attribute Description
class Designates the full package name of the bean.
type Specifies the type of the variable that will refer to the
object.
beanName Gives the name of the bean as specified by the
instantiate
() method of the java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions
before giving a valid
example related to these actions.
The <jsp:setProperty> Action
The setProperty action sets the properties of a Bean. The Bean must
have been previously
defined before this action. There are two basic ways to use the
setProperty action:
You can use jsp:setProperty after, but outside of, a jsp:useBean
element, as below:
<jsp:useBean id="myName" ... />
...
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-154
<jsp:setProperty name="myName" property="someProperty" .../>
In this case, the jsp:setProperty is executed regardless of whether a
new bean was
instantiated or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the
body of a jsp:useBean
element, as below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName" property="someProperty" .../>
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was
instantiated, not if an existing
one was found.
Following is the list of attributes associated with setProperty action:
Attribute Description
name Designates the bean whose property will be set. The Bean
must have been previously defined.
property Indicates the property you want to set. A value of "*"
means that all request parameters whose names match
bean property names will be passed to the appropriate
setter methods.
value The value that is to be assigned to the given property. The
the parameter's value is null, or the parameter does not
exist, the setProperty action is ignored.
param The param attribute is the name of the request parameter
whose value the property is to receive. You can't use both
value and param, but it is permissible to use neither.
The <jsp:getProperty> Action
The getProperty action is used to retrieve the value of a given
property and converts it to a
string, and finally inserts it into the output.
The getProperty action has only two attributes, both of which are
required ans simple syntax
is as follows:
<jsp:useBean id="myName" ... />
...
<jsp:getProperty name="myName" property="someProperty" .../>
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-155
Following is the list of required attributes associated with setProperty
action:
Attribute Description
name The name of the Bean that has a property to be retrieved.
The Bean must have been previously defined.
property The property attribute is the name of the Bean property to
be retrieved.
Example:
Let us define a test bean which we will use in our example:
/* File: TestBean.java */
package action;
public class TestBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
The <jsp:forward> Action
The forward action terminates the action of the current page and
forwards the request to
another resource such as a static page, another JSP page, or a Java
Servlet.
The simple syntax of this action is as follows:
<jsp:forward page="Relative URL" />
Following is the list of required attributes associated with forward
action:
Attribute Description
page Should consist of a relative URL of another resource such
as a static page, another JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jps and (b) main.jsp as
follows:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-156
Following is the content of date.jsp file:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
(b) Explain the OR mapping in hibernate. 07
Solution:
It can be explain as follows:
Persistence
Hibernate ORM is concerned with helping your application to achieve
persistence. So what
is persistence? Persistence simply means that we would like our
application’s data to outlive
the applications process. In Java terms, we would like the state of
(some of) our objects to live
beyond the scope of the JVM so that the same state is available
later.
Relational Databases
Specifically, Hibernate ORM is concerned with data persistence as it
applies torelational
databases (RDBMS). In the world of Object-Oriented applications,
there is often a discussion
about using an object database (ODBMS) as opposed to a RDBMS.
We are not going to
explore that discussion here. Suffice it to say that RDBMS remain a
very popular persistence
mechanism and will so for the foreseeable future.
The Object-Relational Impedance Mismatch
Object-Relational Impedance Mismatch (sometimes called the
paradigm mismatch) is just a
fancy way of saying that object models and relational models do not
work very well together.
RDBMSs represent data in a tabular format (a spreadsheet is a good
visualization for those
not familiar with RDBMSs), whereas object-oriented languages, such
as Java, represent it
as an interconnected graph of objects. Loading and storing graphs of
objects using a tabular
relational database exposes us to 5 mismatch problems…
Granularity
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-157
Sometimes you will have an object model which has more classes
than the number of
corresponding tables in the database (we says the object model is
more granular than the
relational model). Take for example the notion of an Address…
Subtypes (inheritance)
Inheritance is a natural paradigm in object-oriented programming
languages. However,
RDBMSs do not define anything similar on the whole (yes some
databases do have subtype
support but it is completely non-standardized)…
Identity
A RDBMS defines exactly one notion of sameness: the primary key.
Java, however, defines
both object identity a==b and object equality a.equals(b).
Associations
Associations are represented as unidirectional references in Object
Oriented languages
whereas RDBMSs use the notion of foreign keys. If you need
bidirectional relationships in
Java, you must define the association twice.
Likewise, you cannot determine the multiplicity of a relationship by
looking at the object
domain model.
Data navigation
The way you access data in Java is fundamentally different than the
way you do it in a
relational database. In Java, you navigate from one association to
another walking the object
network.
This is not an efficient way of retrieving data from a relational
database. You typically want to
minimize the number of SQL queries and thus load several entities
via JOINs and select the
targeted entities before you start walking the object network.
Q.5 (a) Explain the container architecture of the Java EE with role of
each
component.
Solution:
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-158
Please refer ---- Page no:----- 47
(b) What is HQL? How does it differ from SQL? Give its advantages.
07
Hibernate Query Language (HQL) is same as SQL (Structured Query
Language) but it doesn't
depends on the table of the database. Instead of table name, we use
class name in HQL. So
it is database independent query language.
Advantage of HQL
There are many advantages of HQL. They are as follows:
● database independent
● supports polymorphic queries
● easy to learn for Java Programmer
Query Interface
It is an object oriented representation of Hibernate Query. The object
of Query can be
obtained by calling the createQuery() method Session interface.
The query interface provides many methods. There is given
commonly used methods:
1. public int executeUpdate() is used to execute the update or delete
query.
2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number
from where record will
be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records
to be retrieved from
the relation (table).
5. public Query setParameter(int position, Object value) it sets the
value to the JDBC
style query parameter.
6. public Query setParameter(String name, Object value) it sets the
value to a named
query parameter.
Example of HQL to get all the records
1. Query query=session.createQuery("from Emp");//here persistent
class name is Emp
2. List list=query.list();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-159
Advance Java Technology
Term: WINTER 2013 Subject code: 170703 Date: 09/06/2012
Q.1 (a) Answer the following questions w.r.to Swing. 07
i. What is pluggable look and feel? How do you set the look and feel
of the
components?
ii. Give the limitations of AWT and explain how do Swing overcome
them.
Solution:
i. Refer Page No. 43
ii.Refer Page No. 127
(b) What is JDBC driver? What is its role? List the types of drivers
and explain
working of type-4 driver. Give the different ways to create the JDBC
connection
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-160
with example. 07
Solution:
Refer Page No. 3
Q.2 (a) What is Callable statement? Write a procedure to insert a row
into the table
student(roll_no,name,%ge) and call it using callable statement in
JDBC
application. 07
Solution:
Callable Statement- Refer Page No. 78
Write a procedure to insert a row into the table
student(roll_no,name,%ge) and call it using callable statement in
JDBC
application
Solution:
CREATE OR REPLACE PROCEDURE addStudent
(Rollno Number,Name OUT VARCHAR,GE varchar) AS
BEGIN
Insert into student values(Rollno,Name,GE)
END;
JDBC call Code:
CallableStatement cstmt = null;
try {
String SQL = "{call addStudent (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}
(b) Explain the following classes with their use. 07
i. URLConnection class
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-161
ii. DatagramSocket and DatagramPacket class
Solution:
i Urlconnection Class...Refer Page No. 52
DatagramSocket and DatagramPacket class:-
DatagramPacket class:
The DatagramPacket is message that can be sent or received. If you
send multiple packet,
it may arrive in any order. Moreover, 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();
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-162
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();
}
}
(b) Give the advantages of n-tier architecture and discuss the
objectives of the
Enterprise applications. 07
Solution:
Refer Page. No. 75
Q.3 (a) What is RMI? Give the architecture of RMI and discuss the
functions of each
layer. What is role of RMI registry? 07
Solution:
Refer Page No. 85
(b) What is filter? What is its use? List the different filter interfaces
with their
important methods.
Solution:
Refer Page No.18
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-163
OR
Q.3 (a) What is serialization/deserialization of objects? Why do you
need it? Give the
example with necessary code.
Solution:
Refer Page No. 17
(b) List the servlet session level events and show that how servlet
destroy event is
handled?
Solution:
Refer Page No.27
Q.4 (a) Write a servlet which counts the number of digits into an
integer received as
parameter. Give the necessary web.xml file to deploy the servlet.
import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PageHitCounter extends HttpServlet{
private int hitCount;
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-164
public void init()
{
// Reset hit counter.
hitCount = 0;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// This method executes whenever the servlet is hit
// increment hitCount
hitCount++;
PrintWriter out = response.getWriter();
String title = "Total Number of Hits";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">" + hitCount + "</h2>\n" +
"</body></html>");
}
public void destroy()
{
// This is optional step but if you like you
// can write hitCount value in your database.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-165
}
}
<servlet>
<servlet-name>PageHitCounter</servlet-name>
<servlet-class>PageHitCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageHitCounter</servlet-name>
<url-pattern>/PageHitCounter</url-pattern>
</servlet-mapping>
(b) Explain the JSP implicit objects with their use. 07
Solution:
JSP Implicit Objects are the Java objects that the JSP Container
makes available to
developers in each page and developer can call them directly without
being explicitly
declared. JSP Implicit Objects are also called pre-defined variables.
JSP supports nine Implicit Objects which are listed below:
Object Description
request This is the HttpServletRequest object associated with the
request.
response This is the HttpServletResponse object associated with
the response to the client.
out This is the PrintWriter object used to send output to the
client.
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-166
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with
application context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like
higher performance JspWriters.
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
Exception The Exception object allows the exception data to be
accessed by designated JSP.
The request Object:
The request object is an instance of a
javax.servlet.http.HttpServletRequest object. Each time
a client requests a page the JSP engine creates a new object to
represent that request.
The request object provides methods to get HTTP header
information including form data,
cookies, HTTP methods etc.
We would see complete set of methods associated with request
object in coming chapter:
JSP - Client Request.
The response Object:
The response object is an instance of a
javax.servlet.http.HttpServletResponse object. Just
as the server creates the request object, it also creates an object to
represent the response to
the client.
The response object also defines the interfaces that deal with
creating new HTTP headers.
Through this object the JSP programmer can add new cookies or
date stamps, HTTP status
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-167
codes etc.
We would see complete set of methods associated with response
object in coming chapter:
JSP - Server Response.
The out Object:
The out implicit object is an instance of a javax.servlet.jsp.JspWriter
object and is used to
send content in a response.
The initial JspWriter object is instantiated differently depending on
whether the page is
buffered or not. Buffering can be easily turned off by using the
buffered='false' attribute of the
page directive.
The JspWriter object contains most of the same methods as the
java.io.PrintWriter class.
However, JspWriter has some additional methods designed to deal
with buffering. Unlike the
PrintWriter object, JspWriter throws IOExceptions.
Following are the important methods which we would use to write
boolean char, int, double,
object, String etc.
Method Description
out.print(dataType dt) Print a data type value
out.println(dataType dt) Print a data type value then terminate the
line
with new line character.
out.flush() Flush the stream.
The session Object:
The session object is an instance of javax.servlet.http.HttpSession
and behaves exactly the
same way that session objects behave under Java Servlets.
The session object is used to track client session between client
requests. We would see
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-168
The application Object:
The application object is direct wrapper around the ServletContext
object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext
object.
This object is a representation of the JSP page through its entire
lifecycle. This object is
created when the JSP page is initialized and will be removed when
the JSP page is removed
by the jspDestroy() method.
By adding an attribute to application, you can ensure that all JSP files
that make up your web
application have access to it.
The config Object:
The config object is an instantiation of javax.servlet.ServletConfig
and is a direct wrapper
around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP
engine initialization
parameters such as the paths or file locations etc.
The following config method is the only one you might ever use, and
its usage is trivial:
config.getServletName();
This returns the servlet name, which is the string contained in the
<servlet-name> element
defined in the WEB-INF\web.xml file
Q.5 (a) What are cookies? Write a servlet that reads and prints all the
previous cookies
and add a cookie with your name.
Solution:
Refer Page No.53
(b) Explain the features of core tag library for JSP. 07
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-169
Solution
Refer Page No: 60
OR
Q.5 (a) Explain the following with respect to JSP Unified EL.
i. Value expressions
ii. Method expressions
Solution: Refer Page No. 146
(b) Give the hibernate architecture and discuss each part in brief. 07
Solution:Refer Page No. 66
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-170
Prepared By:Prof.Chintan Dave (SPCE,Visnagar.)
Advance Java Technology
Page-171

Posted by Mayank Patel at 22:57 No comments:


Email ThisBlogThis!Share to TwitterShare to FacebookShare to
Pinterest

Home

Subscribe to: Posts (Atom)


About Me

Mayank Patel
View my complete profile

Blog Archive

 ▼ 2015 (1)
o ▼ May(1)
 gtu ajt paper solution
advance java paper
solution...

Simple theme. Powered by Blogger.

Vous aimerez peut-être aussi