AJ - Lab Manual

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

Silver Oak College of Engineering & Technology

GUJARAT TECHNOLOGICAL UNIVERSITY


BACHELOR OF ENGINEERING

ADVANCED JAVA
(2160707)
6th SEMESTER

INFORMATION TECHNOLOGY

Laboratory Manual

i
VISION
To be recognized for the quality education and research in the field of Information
Technology known for its accomplished graduates.

MISSION

1. Continually improve the standard of our graduates by engaging in innovative teaching


learning methods with high caliber motivated faculty members keeping in-line with the
rapid technological advancements.
2. Promote and support research activities over a wide range of academic interests among
students and staff for growth of individual knowledge and continuous learning.
3. Provide an education system that promotes innovation, creativity, entrepreneurial spirit,
leadership as well as freedom of thought with emphasis on professionalism and ethical
behavior.

Program Educational Objectives (PEO):

PEO1: To provide the fundamentals of science, mathematics, electronics and computer science and
engineering and skills necessary for a successful IT professional.

PEO2: To provide scope to learn, apply skills, techniques and competency to use modern
engineering tools to solve computational problems.

PEO3: To enable young graduates to adapt to the challenges of evolving career opportunities in their
chosen fields of career including higher studies, research avenues, entrepreneurial activities
etc.

PEO4: To inculcate life-long learning aptitude, leadership qualities and teamwork ability with sense
of ethics for a successful professional career in their chosen field.

ii
PROGRAM OUTCOMES (POs) Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change

iii
ADVANCED JAVA PRACTICAL BOOK

DEPARTMENT OF INFORMATION TECHNOLOGY PREFACE

It gives us immense pleasure to present the first edition of Advanced Java Practical Book
for the B.E. 3rd year students of Silver Oak Group of Institutes.

The theory and laboratory course of Advanced Java, at Silver Oak Group of Institutes,
Ahmedabad, is designed in such a manner that students can develop the basic
understanding of the subject during theory classes and gain the hands-on practical
experience during their laboratory sessions. Java being one of the most prominent
languages opens the door to many application developments involving naïves of
Input/output, Networking, the standard utilities, Applets, Frameworks, GUI-based
controls and much more. Many of these concepts were detailed in our first part in Object
Oriented Programming using Java. In this second part of java, Advanced Java, we will
look into networking concepts using TCP/UDP, Java Database Connectivity, web
application development with Servlet, JSP and JSF, frameworks like Hibernate and
Spring.

The Laboratory Manual presented here takes you onto the learning journey of advanced
concepts of Java. In this you will be exploring the wide range of topics like creating a
network application with help of TCP/UDP connection, linking & communication a
database with java application using JDBC, creating a dynamic server side web
application using Servlet, Java Server Pages and Java Server Faces. We will also look into
the hibernate Object Relational Mapping (ORM) framework and application framework
Spring.

Lab Manual Revised by: Prof. Ishan K Rajani, Silver Oak College of Engineering and Technology

Lab Manual Revision No.: SOCET_2160707_LM_2020_1

iv
INSTRUCTIONS TO STUDENTS

1. Be prompt in arriving to the laboratory and always come well prepared for the
experiment.
2. Students need to maintain a proper decorum in the computer lab. Students must use
the equipment with care. Any damage is caused is punishable.
3. Students are instructed to come to lab in formal dresses only.
4. Students are supposed to occupy the systems allotted to them and are not supposed to
talk or make noise in the lab.
5. Students are required to carry their observation book and lab records with completed
exercises while entering the lab.
6. Lab records need to be submitted every week.
7. Students are not supposed to use pen drives in the lab.
8. The grades for the Advanced Java Practical course work will be awarded based on
your performance in the laboratory, regularity, recording of experiments in the
Advanced Java practical Final Notebook, lab quiz, regular viva-voce and end-term
examination.
9. Find the answers of all the questions mentioned under the section, Post Practical
Questions‟ at the end of each experiment in the Advanced Java Practical Book.

v
CERTIFICATE

This is to certify that

Mr./Ms.......................................................................................................................

with enrolment no. ................................................................from Semester

………Div.…….. has successfully completed his/her laboratory experiments in the

ADVANCED JAVA (2160707) from the department of

...................................................................during the academic year ............... -........

Date of Submission: ......................... Staff In charge: ...........................

Head of Department: ...........................................

vi
TABLE OF CONTENT

Page No
Marks
Sr. Date of Date of
Experiment Title Sign (out of
No Start Completion
10)
To From

1.1 Create chat application


using either TCP or UDP
protocol. And Find numeric IP
address (or return error) for
given hostname.
1

1.2 Implement TCP Server for


transferring files using Socket
and ServerSocket.

Implement any one sorting


algorithm using TCP/UDP on
Server application and give
2 input on client side and client
should receive sorted output
from server and display sorted
on input side.
Implement TCP Server
programming in which more
than one client can connect and
3 communicate with Server for
sending the string and server
returns the reverse of string to
each of client.
User can create a new database
4 and also create new table under
that database. Once database
has been created then user can

7
perform database operation by
calling above functions.
4.1 Use this Java Statement
interface to implement program:
Statement
4.2 Use this Java Statement
interface to implement program:
Prepared statement
4.3 Use this Java Statement
interface to implement program:
Callable statement

Create Servlet file which


contains following functions:
1. Connect 2. Create Database
3. Create Table 4. Insert
5 Records into respective table 5.
Update records of particular
table of database 6. Delete
Records from table. 7. Delete
table and also database.
Write a Servlet which counts the
number of digits into an integer
6 received as parameter. Give the
necessary web.xml to
deploy the servlet.
Write a Servlet to create a Login
form with help of request
7 dispatcher. If the login fails, it
should redirect back to login
page, else to the next page.
Write a JSP Program with help
of Bean to demonstrate use of
<jsp:useBean>,
8 <jsp:setProperty> and
<jsp:getProperty> action
elements. It will call JavaBean
from JSP page for Student
Information (First Name, Last

8
Name and Age)
Write a JSP Program with help
of object request to get User
Signup Information in
SessionSignup pag-e.It will pass
9 all these information into
SessionSignupSave page and
use session object and display
the information on
SessionSignup-Display page.
Write a JSP Program to
10 demonst-rate use of Cookies
and URL Rewriting.
11 Study and Implement
Hibernate.
12 Study and Implement Spring
Framework.

9
PRACTICAL SET – 1
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.
The java.net package provides support for the two common network protocols −
TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet Protocol,
which is referred to as TCP/IP.

UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.

The two key classes from the java.net package used in creation of server and client programs are:
ServerSocket
Socket
A server program creates a specific type of socket that is used to listen for client requests (server
socket), In the case of a connection request, the program creates a new socket through which it
will exchange data with the client using input and output streams. The socket abstraction is very
like the file concept: developers must open a socket, perform I/O, and close it. Figure illustrates
key steps involved in creating socket-based server and client programs.

Socket-based client and server programming

1
TCP/IP SOCKET PROGRAMMING

A simple Server Program in Java The steps for creating a simple server program are:

1. Open the Server Socket:


ServerSocket server = new ServerSocket (PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket:
client.close();

A simple Client Program in Java The steps for creating a simple client program are:

1. Create a Socket Object:


Socket client = new Socket (server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();

References:

[1] http://www.buyya.com/java/Chapter13.pdf
[2] Complete Reference J2EE Publisher :McGraw publication

2
Aim 1.1: Create chat application using either TCP or UDP protocol. And Find numeric IP
address (or return error) for given hostname.

Code:

3
4
5
Output:

6
Aim 1.2 Implement TCP Server for transferring files using Socket and ServerSocket

Code:

7
8
Output:

9
Post Practical Questions:

1. Which class is used to create servers that listen for either local client or remote client
programs?
a. ServerSockets
b. httpServer
c. httpResponse
d. None of the above
2. Which methods are commonly used in ServerSocket class?
a. public OutputStream getOutputStream()
b. public Socket accept ()
c. public synchronized void close ()
d. None of the above
3. The client in socket programming must know which information?
a. IPaddress of Server
b. Port number
c. Both A & B
d. None of the above
4. What does the java.net.InetAddress class represent?
a. Socket
b. IP Address
c. Protocol
d. MAC Address

Conclusion:

10
PRACTICAL SET – 2
java.io.DataInputStream.readUTF() Method

Description : The java.io.DataInputStream.readUTF() method reads in a string that has been


encoded using a modified UTF-8 format. The string of character is decoded from the UTF and
returned as String.
Declaration : public final String readUTF()

Parameters: NA

Return Value: This method returns a unicode string.

Exception:
IOException − If the stream is closed or the or any I/O error occurs.
EOFException − If the input stream has reached the ends.
UTFDataFormatException − If the bytes do not represent a valid modified UTF-8 encoding.

java.io.DataOutputStream.writeUTF() Method
Description: The java.io.DataOuputStream.writeUTF(String str) method writes a string to the
underlying output stream using modified UTF-8 encoding.
Declaration: public final void writeUTF(String str)
Parameters: str − a string to be written to the output stream.
Return Value : This method does not return any value.

Exception:
IOException − If an I/O error occurs.

References:

[1] https://www.tutorialspoint.com/java/io/dataoutputstream_writeutf.htm
[2] Complete Reference J2EE Publisher :McGraw publication

11
Aim 2.1 - Implement any one sorting algorithm using TCP/UDP on Server application and give
input on client side and client should receive sorted output from server and display sorted on
inputside.

Code:

12
13
Output:

Post Practical Questions:

1. Which of these streams contains the classes which can work on character stream?
a. InputStream
b. OutputStream
c. Character Stream
d. All of the mentioned
2. Which of these class is used to read characters in a file?
a. FileReader
b. FileWriter
c. FileInputStream
d. InputStreamReader
3. Which of these method of FileReader class is used to read characters from a file?
a. read()
b. scanf()
c. get()
d. getInteger()

14
4. Which of these class can be used to implement the input stream that uses a character
array as the source?
a. BufferedReader
b. FileReader
c. CharArrayReader
d. FileArrayReader
5. Which of these classes can return more than one character to be returned to input stream?
a. BufferedReader
b. Bufferedwriter
c. PushbachReader
d. CharArrayReader

Conclusion:

15
PRACTICAL SET – 3
Datagrams

TCP guarantees the delivery of packets and preserves their order on destination. Sometimes these
features are not required and since they do not come without performance costs, it would be better
to use a lighter transport protocol. This kind of service is accomplished by the UDP protocol which
conveys datagram packets.
Datagram packets are used to implement a connectionless packet delivery service supported by the
UDP protocol. Each message is transferred from source machine to destination based on
information contained within that packet. That means, each packet needs to have destination
address and each packet might be routed differently, and might arrive in any order. Packet delivery
is not guaranteed.
The format of datagram packet is:
| Msg | length | Host | serverPort |
Java supports datagram communication through the following classes:
 DatagramPacket
 DatagramSocket

The class DatagramPacket contains several constructors that can be used for creating packet
object.
One of them is:
DatagramPacket(byte[] buf, int length, InetAddress address, int port);
This constructor is used for creating a datagram packet for sending packets of length length to the
specified port number on the specified host. The message to be transmitted is indicated in the first
argument.
The key methods of DatagramPacket class are:
byte[] getData() : Returns the data buffer.
int getLength() : Returns the length of the data to be sent or the length of the data received.
void setData(byte[] buf) : Sets the data buffer for this packet.
void setLength(int length) : Sets the length for this packet.

The class DatagramSocket supports various methods that can be used for transmitting or
receiving data a datagram over the network.

16
The two key methods are:
void send(DatagramPacket p) : Sends a datagram packet from this socket.
void receive(DatagramPacket p) : Receives a datagram packet from this socket.
A simple UDP server program that waits for client‟s requests and then accepts the message
(datagram) and sends back the same message is given below. Of course, an extended server
program can manipulate client‟s messages/request and send a new message as a response.

DatagramSocket's are Java's mechanism for network communication via UDP instead of TCP.
UDP is still layered ontop of IP. You can use Java's DatagramSocket both for sending and
receiving UPD datagrams.

References:

[1] https://www.tutorialspoint.com/java/io/dataoutputstream
[2] Complete Reference J2EE Publisher :McGraw publication

17
Aim 3.1 : Implement TCP Server programming in which more than one client can connect and
communicate with Server for sending the string and server returns the reverse of string to each of
client.

Code:

18
19
20
Output:

21
Post Practical Questions:

1. Which constructor of DatagramSocket class is used to creates a datagram socket and


binds it with the given Port Number?
a. DatagramSocket(int port)
b. DatagramSocket(int port, InetAddress address)
c. DatagramSocket()
d. None of the above
2. Which classes are used for connection-less socket programming?
a. DatagramSocket
b. DatagramPacket
c. Both A & B
d. None of the above
3. The DatagramSocket and DatagramPacket classes are not used for connection-less
socket programming.
a. True
b. False
4. Datagram is basically an information but there is no guarantee of its content, arrival
or arrival time.
a. True
b. False

Conclusion:

22
PRACTICAL SET – 4
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

 Making a connection to a database.


 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables,
such as −

 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
These different executables can use a JDBC driver to access a database, and take advantage of
the stored data.

The Statement Interface


The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:

1) public ResultSet execute Query(String sql): is used to execute SELECT query. It returns the
object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may be create,

23
drop, insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return multiple
results.

4) public int[] executeBatch(): is used to execute batch of commands.

PreparedStatement
The PreparedStatement interface is a sub interface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?


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

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query) throws SQLException{}

Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given
parameter index.

public void setString(int paramIndex, String sets the String value to the given parameter

24
value) index.

public void setFloat(int paramIndex, float sets the float value to the given parameter
value) index.

public void setDouble(int paramIndex, double sets the double value to the given
value) parameter index.

public int executeUpdate() executes the query. It is used for create,


drop, insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an


instance of ResultSet.

CallableStatement
CallableStatement interface is used to call the stored procedures and functions.

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

What is the difference between stored procedures and functions?


The differences between stored procedures and functions are given below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

25
We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output Function supports only input parameter.
parameters.

Exception handling using try/catch block can Exception handling using try/catch can't be used
be used in stored procedures. in user defined functions.

The prepareCall() method of Connection interface returns the instance of CallableStatement.


Syntax is given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure my procedure that receives 2 arguments.

References:

[1] https://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm

26
Aim : User can create a new database and create new table under that database. Once database
has been created then user can perform database operation by calling above functions.

Aim 4.1 Use this Java Statement interface to implement program: Statement

Code:

27
Output

28
4.2. Use this Java Statement interface to implement program: Prepared statement

Code:

29
30
Output:

31
4.3 Use this Java Statement interface to implement program: Callable statement

Code

32
Output

33
Post Practical Questions:

1. In order to transfer data between a database and an application written in the Java
programming language, the JDBC API provides which of these methods?
a. Methods on the ResultSet class for retrieving SQL SELECT results as Java types.
b. Methods on the PreparedStatement class for sending Java types as SQL statement
parameters.
c. Methods on the CallableStatement class for retrieving SQL OUT parameters as
Java types.
d. All mentioned above
2. Which JDBC type represents a "single precision" floating point number that supports
seven digits of mantissa?
a. REAL
b. DOUBLE
c. FLOAT
d. INTEGER
3. The performance of the application will be faster if you use PreparedStatement interface
because query is compiled only once.
a. True
b. False
4. The intent is for JDBC drivers to implement nonscrollable result sets using the support
provided by the underlying database systems.
a. True
b. False

Conclusion:

34
PRACTICAL SET – 5

Servlets: Servlets are small programs that execute on the server side of a web connection, it
dynamically extends the functionality of a web server. It is used to create a web application that
reside on the server side and generate a dynamic web page.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets. The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol. The
javax.servlet.http package contains interfaces and classes that are responsible for http requests
only. All servlets must implement the javax.servlet.Servlet interface, which defines servlet
lifecycle methods. When implementing a generic service, we can extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and
doPost(), for handling HTTP-specific services.

The servlet life-cycle includes three major functions of a Servlet interface :


1. Initializing a Servlet ( Servlet.init(ServletConfig) ) : init() method is used to initialize a
servlet object. ServletConfig object allows to access name-value configured initialization
parameters & container details.
2. Handling a request ( Servlet.service(ServletRequest, ServletResponse) ) : This stage is
heart of servlet lifecycle, actual request processing is carried out here. ServletRequest
object allows to access client‟s request. ServletResponse object assist servlet to send
response to client. The actual program is handled in this section.
3. Destroying a Servlet ( Servlet.destroy() ) : It is used to release to all servlet instances and
resources. It allows all thread to complete their work and release itself.

The major interfaces of Servlet are:


ServletRequest Interface: It is used to encapsulate client request. It provide important
information about client to Servlet.
ServletResponse Interface: It is used to encapsulate client‟s response. It always listens to a
Servlet object.
ServletConfig Interface: It allows a servlet container to pass information to a servlet. It is used to
initialize a parameter.
ServletContext Interface: ServletContext defines a set of method that a servlet use to
communicate with Servlet Container. It allows parameter to be accessed by all servlets in an
application.
References:
[1] Java-2, The Complete Reference, by Herbert Schildt
[2] https://www.journaldev.com/1877/servlet-tutorial-java

35
Aim : Create Servlet file which contains following functions:
1. Connect 2. Create Database 3. Create Table 4. Insert Records into respective table 5. Update
records of particular table of database 6. Delete Records from table. 7. Delete table and also
database.

Code:

36
37
38
39
Output:

40
Post Practical Questions:
1. When doPost() method of servlet gets called?
a. A POST request results from an HTML form that specifically lists POST as the
METHOD.
b. The service() method checks the HTTP request type as POST and calls doPost()
method.
c. Both of above
d. None of above
2. Which of the following is true about servlets?
a. Servlets are platform-independent because they are written in java
b. Servlets can use the full functionality of the Java class libraries
c. Servlets execute within the address space of web server, platform independent
and uses the functionality of java class libraries
3. How to get a parameter value from a html page into Servlet?
4. What is javax.servlet.http.HttpServlet?
a. interface
b. abstract class
c. concrete class
d. None of above
5. Which life-cycle part of a Servlet plays a important role in its working?
6. Which are the various ways through which a Servlet can be created

Conclusion:

41
PRACTICAL SET – 6

Web.xml : The most important file of a Servlet application is web.xml file. The web.xml file is the
standard deployment descriptor for the Web application that the Web service is a part of. It declares
the filters and servlets used by the service. The general format of the web.xml is as given below.
It includes the servlet which are part of your application and its mapping to the appropriate url-
pattern, through which it can be accessed. All the Servlet used in application are mentioned in the
web.xml file.
<web-app …>
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>Demo1</servlet-name>
<servlet-class>Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>Demo1</servlet-class>
</servlet-mapping>
</web-app>

Apart from the Servlets, filters, listeners, configuration/initialization parameters, error pages,
welcome files, security and session management concepts can be included in web.xml file. The
initialization parameters can be included either for a specific servlet or for all the servlet in a
application, with help of init-param and context-param tags respectively. They can be accessed
with help of methods of ServletConfig and ServletContext interface, alongwith
getinitparameter(name) method. To add a initialization parameter to a particular servlet, it can
written as below, within the servlet tag:

<servlet> ….

<init-param>
<param-name> semester </param-name>
<param-value> 6 </param-value>
</init-param>
</servlet>

References:
[1] Java-2, The Complete Reference, by Herbert Schildt
[2] https://docs.oracle.com/

42
Aim : Write a Servlet which counts the number of digits into an integer received as parameter. Give
the necessary web.xml to deploy the servlet.

Code:

43
44
Output:

Post Practical Questions:


1. What is web.xml and its purpose?
2. How many servlet opening and closing tags can be present in a web.xml file?
3. How can we initialize a parameter for a specific servlet?
4. Which interface can be used to extract the initialization parameter for a specific servlet
and how?
5. How can we initialize a parameter, in web.xml, common for entire application?
6. Which are the various tags in web.xml & its usage?

45
46
47
Conclusion:

48
PRACTICAL SET – 7

RequestDispatcher : Defines an object that receives requests from the client and sends them to
any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates
the RequestDispatcher object, which is used as a wrapper around a server resource located at a
particular path or given by a particular name. This interface is intended to wrap servlets, but a
servlet container can create RequestDispatcher objects to wrap any type of resource. The
RequestDispatcher interface provides two important methods. They are:

1. public void forward(ServletRequest request, ServletResponse response) throws


ServletException, java.io.IOException: Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the server.

2. public void include(ServletRequest request, ServletResponse response) throws


ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.

References
[1] https://docs.oracle.com/javaee/7/api/javax/servlet/RequestDispatcher.html
[2] https://www.javatpoint.com/requestdispatcher-in-servlet

49
Aim: Write a Servlet to create a Login form with help of request dispatcher. If the login fails, it
should redirect back to login page, else to the next page.

Code:

50
51
Output:

Post Practical Questions

1. How can one get an object of a RequestDispatcher in a Servlet file?


2. Which method of a RequestDispatcher can be used add a content into calling resource?
3. How to dispatch a request to a new file?

52
53
Conclusion:

54
PRACTICAL SET – 8

Action Tags: JSP provides various action tags or elements. Each JSP action tag is used to perform
some specific tasks. The action tags are used to control the flow between pages and to use Java
Bean. A Java Bean is a java class that should follow following conventions: It should have a no-
arg constructor. It should be Serializable. It should provide methods to set and get the values of
the properties, known as getter and setter methods. A bean encapsulates many objects into one
object, so we can access this object from multiple places. Here, are mentioned action tags used
with Bean Class:
The <jsp:useBean> action tag is used to locate or instantiate a bean class. If bean object of the
Bean class is already created, it doesn't create the bean depending on the scope. But if object of
bean is not created, it instantiates the bean.
<jsp:useBean id = "students" class = "Bean.StudentBean">

The setProperty and getProperty action tags are used for developing web application with Java
Bean. In web devlopment, bean class is mostly used because it is a reusable software component
that represents data.
The jsp:setProperty action tag sets a property value or values in a bean using the setter method.
<jsp:setProperty name="bean" property="username" value="abc" />

The jsp:getProperty action tag returns the value of the property.


<jsp:getProperty name="obj" property="name" />

References:
[1] https://www.javatpoint.com/jsp-setProperty-and-jsp-getProperty-action-tag
[2] https://www.javatpoint.com/jsp-useBean-action

55
Aim: Write a JSP Program with help of Bean to demonstrate use of <jsp:useBean>,
<jsp:setProperty> and <jsp:getProperty> action elements. It will call JavaBean from JSP page for
Student Information ( First Name, Last Name and Age)

Code:

56
57
Output:

Post Practical Questions:


1. What is Java Bean?
2. Enlist various JSP action tags and its usage.
3. Which JSP tags can be used to retrieve and store data with Bean class?
4. Using which tag can we link a JSP with a Bean Class and how?

58
Conclusion :

59
PRACTICAL SET – 9

JSP implicit objects are created by servlet container while translating JSP page to Servlet source
to help developers. We can use implicit objects in JSP directly in scriptlets that goes in service -
method. However we can‟t use
Object Class Scope
jsp implicit objects in JSP
declaration because that code Out javax.servlet.jsp.JspWriter Page
will go at class level.
Request javax.servlet.ServletRequest Request
We have 9 jsp implicit objects
Response javax.servlet.ServletResponse Page
that we can directly use in JSP
page. Seven of them are declared Session javax.servlet.http.HttpSession Session

as local variable at the start of Application javax.servlet.ServletContext Application


_jspService() method whereas
exception java.lang.Throwable Page
two of them are part of
_jspService() method argument Config javax.servlet.ServletConfig Page
that we can use. Page java.lang.Object Page

PageContext javax.servlet.jsp.PageContext Page

Request Object : It is also an implicit object of class HttpServletRequest class and using this
object request parameters can be accessed.

Syntax:
request.getParameters(“Name”); ( where “Name” is the form element)
Session Object : Session object is of class HttpSession and used to maintain the session
information. It stores the information in Name-Value pair.
Syntax:
session.setAttribute(“Name”,”Id”); | session.getAttribute("Name");
References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] https://www.tutorialspoint.com/jsp/jsp_implicit_objects.htm

60
Aim: Write a JSP Program with help of object request to get User Signup Information (e.g. First
Name, Last Name, User Name and Password) in SessionSignup page.It will pass all these
information into SessionSignupSave page and use session object and display the information on
SessionSignupDisplay page.

Code :

61
62
Output:

Post Practical Questions:


1. Which of the following is not a implicit object?
a. Request
b. Response
c. Cookie
d. session
2. session is instance of which class?
a. Session
b. HttpSession
c. HttpServletSession
d. ServletSession
3. Which of the following method can be used to read a multiple values with same name,
for example check box selections?
a. request.getParameter()
b. response.getParameter()
c. request.getParameterValues()
d. response.getParameterValues()

63
4. “request” is instance of which one of the following classes?
a. Request
b. HttpRequest
c. HttpServletRequest
d. ServletRequest
5. Which attribute uniquely identification element?
a. ID
b. Class
c. Name
d. Scope
6. “out” is implicit object of which class?
a. javax.servlet.jsp.PrintWriter
b. javax.servlet.jsp.SessionWriter
c. javax.servlet.jsp.SessionPrinter
d. javax.servlet.jsp.JspWriter

Conclusion:

64
PRACTICAL SET – 10

In a web application, server may be responding to several clients at a time so session tracking is a
way by which a server can identify the client. As we know HTTP protocol is stateless which means
client needs to open a separate connection every time it interacts with server and server treats each
request as a new request.
Now to identify the client, server needs to maintain the state and to do so , there are several session
tracking techniques.
a) Cookies
b) Hidden Fields
c) URL Rewriting
d) Session Object
Cookie
Cookie is a key value pair of information, sent by the server to the browser and then browser
sends back this identifier to the server with every request there on.
There are two types of cookies:
Session cookies - are temporary cookies and are deleted as soon as user closes the browser. The
next time user visits the same website, server will treat it as a new client as cookies are already
deleted.
Persistent cookies - remains on hard drive until we delete them or they expire.
URL Rewriting
URL Rewriting is the approach in which a session (unique) identifier gets appended with each
request URL so server can identify the user session.

For example if we apply URL rewriting on http://localhost:8080/jsp-tutorial/home.jsp , it will


become something like ?jSessionId=XYZ where jSessionId=XYZ is the attached session identifier
and value XYZ will be used by server to identify the user session.
References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] Professional Java Server Prog by Subrahmanyam Allamaraju, Cedric Buest Wiley Pub.

65
Aim 10.1 - Write a JSP Program to demonstrate use of Cookies.
Code

66
:

67
Output:

68
Aim 10.2 - Write a JSP Program to demonstrate use of URL Rewriting.

Code:

69
Output:

70
Post Practical Questions:
1. Which are the session tracking techniques ?
i. URL rewriting
ii. Using session object
iii.Using response object
iv. Using hidden fields
v. Using cookies
vi. Using servlet object
a - i, ii, iii, vi
b - i, ii, iv, v
c- i, vi, iii, v
d - i, ii, iii, v
2. Which of the following code is used to get session id of a HTTP Session object in
servlets?
a. session.getSessionId()
b. session.getId()
c. session.getActiveId()
d. None of the above
3. Which tag is used to execute java source code in JSP?
a. Declaration Tag
b. Scriptlet tag
c. Expression tag
d. None of the above
4. A JSP page consists of which tags?
a. HTML tags
b. JSP tags
c. Both A & B
d. None of the above

71
5. Which option is true about session scope?
a. Objects are accessible only from the page in which they are created
b. Objects are accessible only from the pages which are in same session
c. Objects are accessible only from the pages which are processing the same request
d. Objects are accessible only from the pages which reside in same application
6. Which of the following are the valid scopes in JSP?
a. request, page, session, application
b. request, page, session, global
c. response, page, session, application
d. request, page, context, application
Conclusion:

72
PRACTICAL SET – 11

It was started in 2001 by Gavin King as an alternative to EJB2 style entity bean. Hibernate is a
pure Java object-relational mapping (ORM) and persistence framework that allows you to map
plain old Java objects to relational database tables. The main goal of hibernate is to relieve the
developer from the common data persistence related tasks. It maps the objects in the java with the
tables in the database very efficiently and also you can get maximum using its data query and
retrieval facilities. Mainly by using Hibernate in your projects you can save incredible time and
effort. Hibernate framework simplifies the development of java application to interact with the
database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool.
Advantages of Hibernate
Opensource and Lightweight: Hibernate framework is
opensource under the LGPL license and lightweight.
Fast performance: The performance of hibernate
framework is fast because cache is internally used in
hibernate framework. There are two types of cache in
hibernate framework first level cache and second level
cache. First level cache is enabled by default.
Database Independent query: HQL (Hibernate Query
Language) is the object-oriented version of SQL. It
generates the database independent queries. So you don't
need to write database specific queries.
Automatic table creation: Hibernate framework provides
the facility to create the tables of the database
automatically. So there is no need to create tables in the
database manually. Directory Structure
Simplifies complex join: To fetch data from multiple tables is easy in hibernate framework.
References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] Hibernate 2nd edition, Jeff Linwood and Dave Minter, Beginning Après publication

73
Aim: Study and Implement Hibernate.

Code:

74
75
76
77
78
79
Output:

80
Post Practical Questions:
1. Hibernate is an?
a. Open Source
b. Lightweight
c. ORM
d. All mentioned above
2. Which of the following element is used to represent one-to-many relationship in
hibernate?
a. <one-to-many>
b. <one-many>
c. <OneToMany>
d. None of the above
3. Which of the following object is used to create SessionFactory object in hibernate?
a. Configuration
b. Session
c. SessionFactory
d. Transaction
4. Which of the following is not an inheritance mapping strategies?
a. Table per hierarchy
b. Table per concrete class
c. Table per subclass
d. Table per class

81
5. Which of these simplifies an Object Relational Mapping tool?
a. Data creation
b. Data manipulation
c. Data access
d. All mentioned above
6. Abbreviate the term HQL?
a. HTTP Queue Language
b. Hibernate Query Language
c. Hipher Query Language
d. None of the above
7. Hibernate framework simplifies the development of java application to interact with the
database.
a. True
b. False
8. What is ORM?
a. Object Rate Mapping
b. Object Relational Mapping
c. Operating Related Mapping
d. Operating Rate Mapping
9. The POJOs stands for
a. Plane Old Java Objects
b. Particular Old Java Objects
c. Plain Open Java Objects
d. Plain Old Java Objects
10. How many layers are available in Hibernate architecture?
a. 3
b. 4
c. 5
d. 2

Conclusion:

82
PRACTICAL SET – 12
It was developed by Rod Johnson in 2003. Spring framework makes the easy development of
JavaEE application. It is helpful for beginners and experienced persons. Spring is a
lightweight framework. It can be thought of as a framework of frameworks because it provides
support to various frameworks such as Struts, Hibernate, EJB, JSF etc. The framework, in broader
sense, can be defined as a structure where we find solution of the various technical problems.
Spring is lightweight when it comes to size and transparency. Spring framework targets to make
J2EE development easier to use and promote good programming practice by enabling a POJO-
based programming model.

Advantages of Spring

 Predefined Templates, Loose Coupling, Easy to test,


Lightweight, Fast Development, Powerful
abstraction, Declarative support.

Spring Framework Directory Structure

References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] Spring in Action 3rd edition , Craig walls, Manning Publication

83
Aim: Study and Implement Spring Framework.

Code:

84
85
86
Output:

Post Practical Questions:


1. Which is the way to provide configuration metadata to spring?
a. XML Based configuration file.
b. Annotation based configuration.
c. Java based configuration.
d. All of the above.
2. What is request scope?
a. This scopes a bean definition to an HTTP request.
b. This scopes the bean definition to Spring IoC container.
c. This scopes the bean definition to HTTP Session.
d. This scopes the bean definition HTTP Application/ Global session.
3. What are the types of the transaction management Spring supports?
a. Programmatic transaction management
b. Declarative transaction management
c. Both of above.
d. None of above.
4. What is true about cross-cutting concerns?
a. The functions that span multiple points of an application are called cross cutting
concerns.
b. Cross-cutting concerns are conceptually separate from the application's business
logic.
c. Logging is one of the examples of cross cutting concerns.
d. All of the above.
5. Which attribute is used to specify classname of the bean?
a. name
b. id
c. class
d. constructor-args
87
6. Declaring bean form object properties can be done using
a. PropertyPathFactoryBean
b. util:constant
c. None of the mentioned
d. All of the mentioned
7. Which class is used to map a database row to a java object in spring?
a. ResultSet
b. RowMapper
c. RowSetMapper
d. ResultSetMapper
8. Which of the following is not a Spring Module ? .
a. AOP
b. O/R Integration
c. Spring MVC
d. HTML/JSP
9. Beans defined in spring framework are by default .. .
a. Abstract
b. Singleton
c. Final
d. initialized
10. Which exception class is related to all the exceptions that are thrown in spring
applications?
a. ArrayIndexOutofBound
b. DataAccessException
c. NullPointerException
d. SpringException

Conclusion:

88

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy