Student Copy AJ IT PDF
Student Copy AJ IT PDF
Student Copy AJ IT PDF
COLLEGE OF TECHNOLOGY
BACHELOR OF ENGINEERING
Advanced Java (1010043339)
6th SEMESTER
College Name:
Name of Student:
Branch:
Semester:
Division:
1
VISION
● To create competent professionals in the field of Information Technology and
promote research with a motive to serve as a valuable resource for the CE/IT
industry and society.
MISSION
1. To produce technically competent and ethically sound Information
Technology professionals by imparting quality education, training, hands on
experience and value based education.
2. To inculcate ethical attitude, sense of responsibility towards society and
leadership ability required for a responsible professional computer engineer.
3. To pursue creative research, adapt to rapidly changing technologies and
promote self-learning approaches in Information Technology and across
disciplines to serve the dynamic needs of industry, government and society.
2
Program Educational Objectives (PEO):
PEO1: To provide the fundamentals of science, mathematics, electronics and
computer science and engineering and skills necessary for a successful CE/ IT
professional.
PEO2: To provide scope to learn, apply skills, techniques and competency to use
modern engineering tools to solve computational problems.
3
PROGRAM OUTCOMES (POs)
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.
4
ADVANCED JAVA PROGRAMMING PRACTICAL BOOK
PREFACE
It gives us immense pleasure to present the first edition of the Basics of Advanced Java
Programming Practical Book for the Degree Engineering 3nd year students of Silver Oak Group of
Institutes.
The Advanced Java Programming theory and laboratory course at Silver Oak Group of Institutes,
Ahmedabad is designed in such a way that students develop the basic understanding of the subject
in the theory classes and gain hands-on practical experience during their laboratory sessions. The
Lab Manual has been designed in such a way that students will get exposure to different kinds of
programs. Difficulty level of programs is increased with each subsequent practical. Students will
get an opportunity to use various sets of instructions. It covers not only practical from the suggested
list of Silver Oak university syllabus but also various programs which have been asked in
university examination. It will surely help students to recall the theoretical knowledge acquired
during lectures and apply it for practical execution of practical. In a way it will draw analogies
between theory and practical and will strengthen the understanding of various topics.
We acknowledge the authors and publishers of all the books which we have consulted while
developing this Practical book. Hopefully this advanced Java Practical Book will serve the purpose
for which it has been developed.
Lab Manual Prepared by: Prof. Shalu Peshwani (ASOIT CE/IT Department)
5
CERTIFICATE
Mr./Ms................................................................................................................
........
6
TABLE OF CONTENT
Page No Date
Sr. Date of Marks
Experiment Title of Sign
No Completion (out of 10)
To From Start
7
PRACTICAL-1
Description:
TCP sockets are used for communication between a server and a client process. The server’s code runs
first, which opens a port and listens for incoming connection requests from clients. Once a client connects
to the same (server) port, the client or server may send a message. Once the message is sent, whoever
receives it (server or client) will process it accordingly.
Socket Programming
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 the 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 the port number to connect to.
● The constructor of the Socket class attempts to connect the client to the specified server and
the 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 two-way communication protocol, hence data can be sent across both streams at the same time.
Following are the useful classes providing complete set of methods to implement sockets.
8
Aim: Implement TCP Server for transferring files using Socket and ServerSocket.
Code:
9
10
OUTPUT:
Conclusion:
11
PRACTICAL - 2
Description:
To write an RMI Java application, you would have to follow the steps given
below −
● Define the remote interface
● Develop the implementation class (remote object)
● Develop the server program
● Develop the client program
● Compile the application
● Execute the application
12
● Export the remote object using the method exportObject() of the class named
UnicastRemoteObject which belongs to the package java.rmi.server.
● Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
● Bind the remote object created to the registry using the bind() method of the class named
Registry. To this method, pass a string representing the bind name and the object exported,
as parameters.
To this method, you need to pass a string value representing the bind name as a parameter. This will
return you the remote object.
● The lookup() returns an object of type remote, down-cast it to the type Hello.
● Finally invokes the required method using the obtained remote object.
Aim: Write an RMI application where client supplies two numbers and server response by
summing it. Provide your custom security policy for this application.
Code:
13
14
15
OUTPUT:
3. RMI and EJB, provides services to access an object running in another JVM (known as remote
object).
A) True B)False
4. What are the exceptions which have to be handled in a RMI client program?
A) RemoteException
B) NotBoundException
C) MalFormedURLException
D) All mentioned above
Conclusion:
16
PRACTICAL - 3
Description:
Step 1 : Registering The Driver Class
First step in establishing the connection with any database is registering the JDBC driver class of that
database with DriverManager. As we are using Oracle database in our examples, we register
‘oracle.jdbc.driver.OracleDriver‘ class, which is the JDBC driver class of the Oracle, with the
DriverManager. As this step has to be performed only once for the whole execution, it is better to keep
this step in Static Initialization Block. Don’t forget to update your classpath with JDBC driver of the
Oracle database. Otherwise you will get ClassNotFoundException at run time.
17
Aim: Implement student registration form with enrolment number, first name, last name,
semester, contact number. Store the details in a database(JDBC). Also implement search, delete
and modify facilities for student records.
Code:
18
19
20
Output:
21
Post Practical Questions:
1. What does setAutoCommit(false) do?
A)It will not commit transactions automatically after each query.
B)It explicitly commits the transaction.
C)It never commits the transactions.
D)It does not commit transaction automatically after each query.
2. A good way to debug JDBC-related problems is to enable?
A)JDBC tracing
B)Exception handling
C)Both a and b
D)Only b
3. JDBC-ODBC driver is also known as?
A)Type 4
B)Type 3
C)Type 1
D)Type 2
4. What are the types of ResultSet in JDBC?
A)Forward ResultSet
B)Scrollable ResultSet
C)Only a
D)Both a and b
5. How many statement objects can be created using a Connection?
A)2
B)1
C)3
D)Multiple
Conclusion:
22
PRACTICAL - 4
Description:
One of the most important advantages of using Servlet is that you can use most of the methods
available in core Java. This tutorial would take you through Java provided Date class which is available
in java.util package, this class encapsulates the current date and time. The Date class supports two
constructors. The first constructor initializes the object with the current date and time.
Date( )
The following constructor accepts one argument that equals the number of milliseconds that have
elapsed since midnight, January 1, 1970
Date(long millisec)
Simple DateFormat Format Codes
To specify the time format use a time pattern string. In this pattern, all
ASCII letters are reserved as pattern letters, which are defined as the
following −
Character Description Example
G Era designator AD
d Day in month 10
m Minute in hour 30
23
s Second in minute 55
S Millisecond 234
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
Code:
24
Output:
25
2. Which of the following code is used to get a particular attribute in servlet?
A) request.getAttribute(name) B) response.getAttribute(name)
C) new Attribute(name) D) None of the above.
3. Which of the following code is used to set auto refresh of a page after 5 seconds?
A) session.setIntHeader("Refresh", 5) B) response.setIntHeader("Refresh", 5)
C) request.setIntHeader("Refresh", 5) D) None of the above.
Conclusion:
PRACTICAL - 5
Description:
Servlet technology is used to create a web application (resides at server side and generates a dynamic
web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming language.
However, there were many disadvantages to this technology. We have discussed these disadvantages
below. There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
26
Aim: Create Servlet file and study web descriptor file
Code:
27
28
Post Practical Questions:
A)True B)False
A) True B) False
A) The destroy() method is called only once at the end of the life cycle of a filter
B) The destroy() method is called after the filter has executed doFilter method
C) The destroy() method is called only once at the beginning of the life cycle of a filter
D) The destroyer() method is called after the filter has executed
Conclusion:
29
PRACTICAL- 6
Description
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by
the user, cookie is added with request by default. Thus, we recognize the user as the old user.
30
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is removed
only if user logout or signout.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in
servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user
requests to the server, server treats the request as the new request. So we need to maintain the state of an
user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given
below:
00:00/06:31
10
31
Aim: Create login form and perform state management using Cookies, HttpSession and URL
Rewriting.
Code:
32
33
34
35
36
Output:
37
PRACTICAL - 7
Description:
JSP technology is used to create web application just like Servlet technology. It can be thought of as an
extension to Servlet because it provides more functionality than servlet such as expression language,
JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tags, etc.
38
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The
JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet.
After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like initialization, committing response
to the browser and destroy.
In this article, I am going to discuss How to interact with a Database in JSP Application. Please read our
previous article, where we discussed JSP Standard Tag Library (JSTL) with Examples. As part of this
article, we are going to discuss the following pointers.
In JSP, we are using databases for storing huge types of data. We can easily connect with databases to
create and manage records. JSP has a number of actions for database access to improve the simple
database-driven JAP applications. These actions provide the following features:
Aim: Create database of student subject-wise data and retrieve all data using JSP and generate xml
structure along with DTD and XML Schema definition.
39
Code:
40
41
42
Output:
2. Which tag should be used to pass information from JSP to included JSP?
A) Using <%jsp:page> tag
B) Using <%jsp:param> tag
C) Using <%jsp:import> tag
D) Using <%jsp:useBean> tag
43
A) UNIQUE
B) SEQUENCE
C) AUTO_INCREMENT
D) None of the mentioned
7. The doGet() method in the example extracts values of the parameter’s type and number by using
__________
A) request.getParameter()
B) request.setParameter()
C) responce.getParameter()
D) responce.getAttribute()
Conclusion:
PRACTICAL - 8
Description:
Java Server Faces (JSF) is a Java-based web application framework intended to simplify development
integration of web-based user interfaces. JavaServer Faces is a standardized display technology, which
was formalized in a specification through the Java Community Process.
JSF application life cycle consists of six phases which are as follows
−
44
Aim:Design a web page that takes the Username from user and if it is a valid username prints
“Welcome Username”. Use JSF to implement.
Code:
45
46
Output:
47
3. .......... isn't a directive.
A) page B) export
C) include D)useBean
Conclusion:
PRACTICAL - 9
Description:
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is 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 relieves the developer from 95% of common data persistence related programming
tasks.
Hibernate sits between traditional Java objects and database server to handle all the works in persisting those
objects based on the appropriate O/R mechanisms and patterns.
48
Supported Databases
Hibernate supports almost all the major RDBMS. Following is a list of few of the
database engines supported by Hibernate −
● HSQL Database Engine
● DB2/NT
● MySQL
● PostgreSQL
● FrontBase
● Oracle
● Microsoft SQL Server Database
● Sybase SQL Server
● Informix Dynamic Server
Aim: Write Hibernate application to store customer records and retrieve the customer record
including name, contact number, address.
Code:
49
50
51
52
53
Output:
2. Session.createSQLQuery creates a new instance of Query for the given HQL query string.
A)true B) false
54
B) Easy to write query
C) No need to learn SQL
D) Difficult to implement
A) Session.read() B) Session.get()
C) Session.retrieve() D) Session.fetch()
Conclusion:
PRACTICAL - 10
Description:
Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web
applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and
responses. It dispatches the requests to handlers. It uses @Controller and @RequestMapping as default request
handlers. The @Controller annotation defines that a particular class is a controller. @RequestMapping
annotation maps web requests to Spring Controller methods. The terms model, view, and controller are as
follows:
Model: The Model encapsulates the application data.
View: View renders the model data and also generates HTML output that the client’s browser can interpret.
Controller: The Controller processes the user requests and passes them to the view for rendering.
55
4. The DispatcherServlet checks the entry of the view resolver in the XML file and invokes the
appropriate view component.
Advantages of Spring MVC Framework
● The container is used for the development and deployment of applications and uses a lightweight
servlet.
● It enables rapid and parallel development.
Aim:Write an application to keep record and retrieve record of student. The record includes student
id, enrolment number, semester, SPI. Use MVC architecture.
Code:
56
57
58
59
60
61
Output:
2. A bean can have more than one name using multiple id attributes?
62
A)true B) false
Conclusion:
63