Practical 1 2 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

A Laboratory Manual for

Advance Java Programming


(3160707)

B.E. Semester 6 (Computer)

Directorate of Technical Education, Gandhinagar,


Gujarat
Vishwakarma Government Engineering College
Certificate

This is to certify that Mr./Ms.


Enrollment No. of B.E. Semester
Computer Engineering of this Institute (GTU Code: ) has satisfactorily
completed the Practical / Tutorial work for the subject Advance Java
Programming (3160707) for the academic year 2022-23.

Place:
Date:

Name and Sign of Faculty member Head of the Department


Advance Java Programming (3160707)

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome-based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-based curriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed
to focus on the industry defined relevant outcomes, rather than old practice of conducting
practical to prove concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

Advance Java Programming is an Elective course. It covers various java based technologies like
socket, JDBC, Servlet and JSP which help students to develop enterprise application. Web
application based on Java uses Servlet, JSP, JSF etc. To store the data database connectivity and
database JDBC component is needed. Networking components are needed to transfer data over
network. Model-View-Controller (MVC) architecture gives flexibility and makes the web
applications loosely coupled.

Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal
of errors if any.
Advance Java Programming (3160707)

DTE’s Vision

 To provide globally competitive technical education


 Remove geographical imbalances and inconsistencies
 Develop student friendly resources with a special focus on girls’ education and support to
weaker sections
 Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision

 To create an ecosystem for proliferation of socially responsible and technically sound


engineers, innovators and entrepreneurs.

Institute’s Mission

 To develop state-of-the-art laboratories and well-equipped academic infrastructure.


 To motivate faculty and staff for qualification up-gradation, and enhancement of subject
knowledge.
 To promote research, innovation and real-life problem-solving skills.
 To strengthen linkages with industries, academic and research organizations.
 To reinforce concern for sustainability, natural resource conservation and
social responsibility.

Department’s Vision

 To create an environment for providing value-based education in Computer Engineering


through innovation, team work and ethical practices.

Department’s Mission

 To produce computer engineering graduates according to the needs of industry,


government, society and scientific community.
 To develop state of the art computing facilities and academic infrastructure.
 To develop partnership with industries, government agencies and R & D organizations for
knowledge sharing and overall development of faculties and students.
 To solve industrial, governance and societal issues by applying computing techniques.
 To create environment for research and entrepreneurship.
Advance Java Programming (3160707)

Programme 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 analyzecomplex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineeringproblems 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 knowledgeand 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 contextualknowledge 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 professionalengineering
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 andresponsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as amember or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activitieswith 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 understandingof 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 abilityto engage in
independent and life-long learning in the broadest context of technological change.
Advance Java Programming (3160707)

Program Specific Outcomes (PSOs)

 Sound knowledge of fundamentals of computer science and engineering including


software and hardware.
 Develop the software using sound software engineering principles having web
based/mobile based interface.
 Use various tools and technology supporting modern software frameworks for solving
problems having large volume of data in the domain of data science and machine learning.

Program Educational Objectives (PEOs)

 Possess technical competence in solving real life problems related to Computing.


 Acquire good analysis, design, development, implementation and testing skills to
formulate simple computing solutions to the business and societal needs.
 Provide requisite skills to pursue entrepreneurship, higher studies, research, and
development and imbibe high degree of professionalism in the fields of computing.
 Embrace life-long learning and remain continuously employable.
 Work and excel in a highly competence supportive, multicultural, and professional
environment which abiding to the legal and ethical responsibilities.
Advance Java Programming (3160707)

Practical – Course Outcome matrix

Course Outcomes (COs):


CO_3160707.1 Implement Networking and Data base connectivity in Java for given application.
CO_3160707.2 Implement webpage with dynamic content and server side web application
using Servlet and JSP.
CO_3160707.3 Use web application framework JSF to build user interfaces.
CO_3160707.4 Use Object Relation Mapping using Hibernate to build database
dependent applications
CO_3160707.5 Apply Model-View-Controller architecture to build complex client-server
applications.
Sr. CO CO CO CO CO
Objective(s) of Experiment
No. 1 2 3 4 5
Create databases related to your project and query them
1. √
from console based java applications.
Create a client application that will connect with the
application mentioned in the practical 1, client
application will send a search “string” to the above
2. √
application and above application will send back the
string with the matching results after fetching from the
database.
Modify practical 1 by replacing the console based user
3. √
interface to a web based user interface. Use a servlet.
4. Modify the practical 4 to use JSP instead of Servlet. √
Use JSF framework to replace JSP and calculate the
5. √
reduction in programming
Make custom tag for a component that will be able to
6. √
add/view/delete/modify Records
Use Object Relational Mapping and based on that
prepare one configuration file along with the hibernet
7. √
mapping file for 1 table of the application and test its
working by replacing SQL to HQL.
Use Hibernet framework to replace JDBC calls and
8. calculate the reduction in programming efforts for the √
entire application
Use Spring or any other MVC architecture and
9. implement the Interface in that architecture that √
supports multi-tier architecture.
Compare and analyze the JSF with the Spring
10. √
framework.
Advance Java Programming (3160707)

Industry Relevant Skills

The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to develop web application using Netbeans/Ecllipse IDE
2. Will be able to use MVC architecture for application development
3. Will be able to use JSF and Hibernate framework

Guidelines for Faculty members


1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students
before starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the
students and ensure that the respective skills and competencies are developed in the
students after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students


1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination
scheme, skill set to be developed etc.
2. We will have a project based learning methodology for practical in Advanced Java subject.
3. Students will form a team of maximum 4 people and then give the definition of a project..
4. Students can use the web application definition of Design Engineering subject also/ They
can give another definition for a web application project
5. You'll need to decide the project and submit your practical list sample list is shown in next
page.
6. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.

Common Safety Instructions


Students are expected to
1) switch on the PC carefully (not to use wet hands)
2) shutdown the PC properly at the end of your Lab
3) carefully Handle the peripherals (Mouse, Keyboard, Network cable etc)
4) Use Laptop in lab after getting permission from Teacher
Advance Java Programming (3160707)

Sample Practical List


Project Name: Portfolio Website

Project Details: Portfolio website to showcase individual skills to the business


world. A website where people can upload their portfolio which consist of their
education , skills , experiences , and social media handles which can help them
them het hired by the companies whose requirement matches with the skills of
the person. Here people can share about their achievements and projects so that
they can connect with the people with same interests and professions. This
website will help people make appropriate connections that will help them move
forward in their career. It will also help students find internships and mentorship
that they need ton pursue their desired goal.

Sr. Objective(s) of Experiment


No.

1 In java console application, provide the user with following options: add, view, modify
details, delete details. On entering a particular option on the console by user, perform
appropriate operation and display the success/failure or any output on your console.

2 Make the practical 1 application as server for sending/receiving strings. Create a client
application that will send a search book string to the server application and server will
replay with the matching book name “string” back to the client application after
fetching from the database.
3 Modify practical 1 by replacing the console based user interface to a web based user
interface. Use a servlet.
4
Modify the practical 4 to use JSP instead of Servlet.
5
Use JSF framework to replace JSP and calculate the reduction in programming
6 Make custom tag for a component that will be able to add/view/delete/modify
Records
7 Use Object Relational Mapping and based on that prepare one configuration file
along with the hibernet mapping file for 1 table of the application and test its working
by replacing SQL to HQL.
8 Use Hibernet framework to replace JDBC calls and calculate the reduction in
programming efforts for the entire application
9 Use Spring or any other MVC architecture and implement the Interface in that
architecture that supports multi-tier architecture.
10
Compare and analyze the JSF with the Spring/any other framework.
Advance Java Programming (3160707)

Index
(Progressive Assessment
Sheet)

Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar


No. No. perform submiss nt Teacher ks
ance ion Marks with date

Total
Experiment No: 1

In java console application, provide the user with following options: add, view, modify
details, delete details. On entering a particular option on the console by user, perform
appropriate operation and display the success/failure or any output on your console.

Date:

Competency and Practical Skills: programming and database commands

Relevant CO: CO1

Objectives: (a) To show use of JDBC Drivers.


(b) To show how java program can interact with Database
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse, Oracle
Xpress edition 11g, Type4 JDBC driver for Oracle

Theory:
A JDBC program comprises the following FIVE steps:
 STEP 1: Allocate a Connection object, for connecting to the database server.
 STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL command.
 STEP 3: Write a SQL query and execute the query, via the Statement and Connection created.
 STEP 4: Process the query result.
 STEP 5: Close the Statement and Connection to free up the resources.

Safety and necessary Precautions:

1) Make sure the database server is started before running the program
2) Handle all necessary compile time Exception

Procedure:
1. Create a database for your project
2. Write java program to interact with tables in database using Type 4 JDBC driver.
Observations:

import java.sql.*;

class data {
int sid;
String s_name;
String s_email;
String s_phone;

data(int sid, String s_name, String s_email,String s_phone) {


this.sid = sid;
this.s_name = s_name;
this.s_email = s_email;
this.s_phone = s_phone;

}
}

public class Driver {

static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";


static final String url = "jdbc:mysql://localhost:5010/portfolio";
static final String uname = "root";
static final String pass = "tanmay10";

public static Connection getConnection() throws Exception {


Class.forName(JDBC_DRIVER);
return DriverManager.getConnection(url, uname, pass);
}

static void createTable(Statement Stmt) {


try {
String sql = "CREATE TABLE student " +
"(sid INT, " +
"s_name VARCHAR(20) not null, " +
"s_email VARCHAR(50) not null unique, " +
"s_phone CHAR(10), not null unique " +
"PRIMARY KEY (sid))";
Stmt.executeUpdate(sql);

} catch (Exception e) {

System.out.println(e);
}
}

static void insertstudentDetail(Statement stmt, data newData) {


try {
String sql = "INSERT INTO student(sid, s_name, s_email, s_phone) "
+
"VALUES(" + newData.sid + ", '" +
newData.s_name + "', '" + newData.s_email +
"', " + newData.s_phone + ", ')";

stmt.executeUpdate(sql);
} catch (Exception e) {

System.out.println(e);
}
}

static ResultSet searchData(Statement stmt) {


try {
String sql = "SELECT sid" +
",s_name,s_email,s_phone form student";
ResultSet rs = stmt.executeQuery(sql);
return rs;
} catch (Exception e) {
System.out.println(e);
}
return null;
}

static void updatestudentDetail(Statement stmt, data updatedData) {


try {
String sql = "UPDATE student " +
"SET s_name = '" + updatedData.s_name + "', " +
"s_email = '" + updatedData.s_email + "', " +
"s_phone = " + updatedData.s_phone + ", " +
"WHERE sid = " + updatedData.sid;
stmt.executeUpdate(sql);

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

static void deletestudentDetail(Statement stmt, int sid) {


try {
String sql = "DELETE FROM student WHERE sid " +
" = " + sid;
stmt.executeUpdate(sql);
} catch (Exception e) {
System.out.println(e);
}
}

static ResultSet searchData(Statement stmt, String searchString) {


ResultSet rs = null;
try {
String sql = "SELECT sid, s_name, s_email, s_phone FROM student " +
"WHERE sid LIKE '%" + searchString +
"%' OR s_name LIKE '%" + searchString +
"%' OR s_email LIKE '%" + searchString +
"%' OR s_phone LIKE '%" + searchString + "%'";
rs = stmt.executeQuery(sql);

} catch (Exception e) {
System.out.println();
}
return rs;
}

static String getSearchResult(ResultSet rs) throws Exception {


StringBuilder searchResult = new StringBuilder();
while (rs.next()) {
String s_name = rs.getString("s_name");
String s_email = rs.getString("s_email");
String s_phone = rs.getString("s_phone");
if (s_name!= null && s_email != null && s_phone != null) {
searchResult.append(s_name).append("|");
searchResult.append(s_email).append("|");
searchResult.append(s_phone).append("|");
searchResult.append("\n");
}
}
return searchResult.toString();
}

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
conn = getConnection();
stmt = conn.createStatement();
createTable(stmt);
insertstudentDetail(stmt, new data(3, "dakshesh", "[email protected]", "8752832478" ));
updatestudentDetail(stmt,new data(2, "princy", "[email protected]", "9567537850" ));

// deletestudentDetail(stmt,2);

rs = searchData(stmt, "");

System.out.println(getSearchResult(rs));
stmt.close();
conn.close();

} catch (SQLException se) {


se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// close resources
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
System.out.println(e);
}
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
System.out.println(e);
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
}

Output :

 Insert details

 Update details
 Delete details
Conclusion:

JDBC API can be used in order to access the tabular data stored in any of the relational
databases. By using JDBC API, you can save, update, delete, and fetch the data from the database.
Therefore, it is considered to be Open Database Connectivity, that is, ODBC provided by
Microsoft.

Quiz:
1) List and explain all four types of JDBC Drivers.
2) What is parameterised query? How it can be executed in java?
3) Write a note on various APIs of java.sql package.

Suggested Reference:
JDBC™ API Tutorial and Reference, Third Edition, Maydene Fisher, Jon Ellis, Jonathan Bruce, Addison
Wesley
References used by the students:
JDBC™ API Tutorial and Reference, Third Edition, Maydene Fisher, Jon Ellis, Jonathan Bruce, Addison
Wesley

https://www.geeksforgeeks.org/establishing-jdbc-connection-in-java/ Rubric wise

marks obtained:
Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)

Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 2

Make the practical 1 application as server for sending/receiving strings. Create a client
application that will send a search string to the server application and server will replay
with the matching name “string” back to the client application after fetching from the
database.

Date:

Competency and Practical Skills: programming and database commands

Relevant CO: CO1

Objectives: (a) To show how to implement TCP/UDP communication between two java
program using Socket/ ServerSocket and DatagramSocket/DatagramPacket.
(b) To show how to implement client server relationship between programs.
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse

Theory:
Java Networking Terminology: IP Address, Protocol, Port Number, MAC Address, Connection-oriented
and connection-less protocol, Socket

1) IP Address: IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is


composed of octets that range from 0 to 255. It is a logical address that can be changed.

2) Protocol: A protocol is a set of rules basically that is followed for communication. For example: TCP,
FTP, Telnet, SMTP, POP etc.

3) Port Number: The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications. The port number is associated with the IP address for
communication between two applications.

4) MAC Address: MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address. For example, an
ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol: In connection-oriented protocol, acknowledgement is


sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP. But, in
connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.

6) Socket : A socket is an endpoint between two way communications.

java.net package

The java.net package can be divided into two sections: A Low-Level API: It deals with the abstractions of
addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and
Interfaces i.e. network interfaces .A High Level API: It deals with the abstraction of URIs i.e. Universal
Resource Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the
resource pointed by URLs.
Safety and necessary Precautions:
1. Make sure the server/receiver program runs first
2. Handle all necessary compile time Exception

Procedure:
1. Create a Sender/Client program and Receiver/Server program.
2. Compile them
3. Run Server/Receiver program first and then run Client/Sender program

Observations:

//server side

import java.io.IOException;
import java.net.*;
import java.sql.*;
import Driver;
public class Server extends Driver{
private static final int PORT = 12345; // the port number the server listens on
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server listening on port " + PORT);

// listen for incoming client connections


while (true) {
// accept incoming client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
Connection connection = getConnection();

// create new thread to handle search request


Thread thread = new Thread(() -> {
try {

// handle search request


ResultSet resultSet = searchData(connection.createStatement(), "Java");
String searchResult = getSearchResult(resultSet);
clientSocket.getOutputStream().write(searchResult.getBytes());
System.out.println("Search result sent to client.");
} catch (Exception e) {
System.out.println("Error handling search request: " + e.getMessage());
} finally {

// close client connection


try {
clientSocket.close();
System.out.println("Client disconnected.");
} catch (IOException e) {
System.out.println("Error closing client connection: " + e.getMessage());
}
}
});
thread.start();
}
} catch (Exception e) {
System.out.println(e);
}
}
}

//client side

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {

try {
// Establish socket connection with server application
Socket socket = new Socket("localhost", 12345);
// Send search string to server application

OutputStream output = socket.getOutputStream();


PrintWriter writer = new PrintWriter(output, true);
writer.println("Java");

// Receive matching results from server application


InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close socket connection


socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:

(server)

(client)
Conclusion:

This practical based on TCP Connection based Protocol. Now client request to the server using
port and client enter the string and server will response .

Quiz:
1. Explain InetAddress class and its use in network programming.
2. With the help of example show the use of URL and URLConnection class.
3. How can we do network programming using UDP in java? Explain DatagramSocket and
DatagramPacket in Java.

Suggested Reference: Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric


Buest Wiley Publication

References used by the students: Professional Java Server Programming by Subrahmanyam


Allamaraju, Cedric Buest Wiley Publication

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)

Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 3
Modify practical 1 by replacing the console based user interface to a web based user interface.
Use a servlet.

Date:

Competency and Practical Skills: Design a web application using Servlet

Relevant CO: CO2

Objectives: (a) implement webpages using HTML for collecting user input.
(b) able to do server side programming using Servlet to process user input.
(c) To show how Servlet can interact with Database
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Apache Tomcat Server,
Netbeans/eclipse, Oracle Xpress edition 11g, Type4 JDBC driver for Oracle

Theory:
• Servlet technology is used to create web application
• Servlet technology is robust and scalable because of java language.
• Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a
server-side programming language.
• There are many interfaces and classes in the servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse etc.
Servlet APIs
• javax.servlet and javax.servlet.http
• javax.servlet package contains many interfaces and classes that are used by the servlet or web
container.
• javax.servlet.http package contains interfaces and classes that are responsible for http requests
The servlet can be created by three ways: By
implementing Servlet interface, By
inheriting GenericServlet class, By
inheriting HttpServlet class
• The mostly used approach is by extending HttpServlet. The
steps are as follows:
• Create a directory structure
• Create a Servlet
• Compile the Servlet
• Create a deployment descriptor
• Start the server(Apache tomcat) and deploy the project
• Access the servlet

Safety and necessary Precautions:


1. Make sure the database server and application server are started before running the
program
2. Put you application directory in to root directory of Tomcat server
3. To run the program use any web browser
4. Handle all necessary compile time Exception

Procedure:
1. Create a directory structure for web application in application folder.
2. Create database for your project
3. Create an html file asking for data from user and submit those data to servlet in application
folder
4. Create a servlet class to receive the input and process it as per your requirement, Also this
servlet program can interact with database using Type 4 JDBC driver.
5. Prepare web.xml file to put deployment descriptor
6. Compile to servlet program
7. Put application folder into root directory of application server( wepapps folder of Tomcat
server)
8. Open any web browser and run the program by typing url in address bar.

Observations:

package tanmay;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
*
* @author HP
*/
public class tanmay {
public static void main(String[] args){
public class MaterialServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Display the user interface using HTML forms


out.println("<html><body>");
out.println("<h2>student Detail</h2>");
out.println("<form action=\"MaterialServlet\" method=\"post\">");
out.println("sid: <input type=\"text\" name=\"sid\"><br>");
out.println("s_name: <input type=\"text\" name=\"s_name\"><br>");
out.println("s_email: <input type=\"text\" name=\"s_email\"><br>");
out.println("s_phone: <input type=\"text\" name=\"s_phone\"><br>");
out.println("publisher: <input type=\"text\" name=\"publisher\"><br>");
out.println("language: <input type=\"text\" name=\"language\"><br>");
out.println("year: <input type=\"text\" name=\"year\"><br>");
out.println("Search : <input type=\"text\" name=\"search\"><br>");
out.println("Operation:");
out.println("<select name=\"operation\">");
out.println("<option value=\"add\">Add</option>");
out.println("<option value=\"view\">View</option>");
out.println("<option value=\"modify\">Modify</option>");
out.println("<option value=\"delete\">Delete</option>");
out.println("</select><br>");
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form>");
out.println("</body></html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieve the user's input


String sidStr = request.getParameter("sid");
int sid;
if (sidStr == null || sidStr.isEmpty()) {
sid = 0;
} else {
sid = Integer.parseInt(sidStr);
}
String s_name = request.getParameter("s_name");
String s_email = request.getParameter("s_email");

// int s_phone = Integer.parseInt(request.getParameter("s_phone"));


String s_phoneStr = request.getParameter("s_phone");
int s_phone;
if (s_phoneStr == null || s_phoneStr.isEmpty()) {
s_phone = 0;
} else {
s_phone = Integer.parseInt(s_phoneStr);
}
String publisher = request.getParameter("publisher");
int year = Integer.parseInt(request.getParameter("year"));
String language = request.getParameter("language");
String operation = request.getParameter("operation");
String search = request.getParameter("search");
Connection conn = null;
Statement stmt = null;
try {
conn = Driver.getConnection();
stmt = conn.createStatement();

// Perform the appropriate operation based on the selected option


if (operation.equals("add")) {
Driver.insertstudentDetail(stmt, new Data(sid, s_name, s_email, s_phone, publisher, year, language));
out.println("<html><body>");
out.println("<h2>student Added Successfully!</h2>");
out.println("</body></html>");

} else if (operation.equals("view")) {
ResultSet rs = Driver.searchData(stmt, search);
String searchResult = Driver.getSearchResult(rs);
out.println("<html><body>");
out.println("<h2>student Details</h2>");
out.println("<pre>" + searchResult + "</pre>");
out.println("</body></html>");

} else if (operation.equals("modify")) {
Driver.updatestudentDetail(stmt, new Data(sid, s_name, s_email, s_phone, publisher, year, language));
out.println("<html><body>");
out.println("<h2>student Modified Successfully!</h2>");
out.println("</body></html>");
} else if (operation.equals("delete")) {
Driver.deletestudentDetail(stmt, sid);
out.println("<html><body>");
out.println("<h2>student Deleted Successfully!</h2>");
out.println("</body></html>");

} else {
out.println("<html><body>");
out.println("<h2>Invalid operation!</h2>");
out.println("</body></html>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {

try {
if (stmt != null) {
stmt.close();
}

if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

Output:

Html:-

Database:-
Conclusion:

This are servlet class using this servlet class Make a interface and make form in the interface.
Now if user add the data in the form and select the add Data and that Data add in the Database and
if user wish to delete data than select delete and than Data was deleted and many other operation
can do.

Quiz:
1. List various characteristics of Enterprise application.
2. Draw and explain servlet life cycle.
3. Compare servlet with JSP.
4. What is session tracking? How can we implement it in Servlet?

Suggested Reference:
Complete Reference J2EE by James Keogh mcgraw publication
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley Publication

References used by the students:

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)

Rubrics 1 2 3 4 5 Total
Marks

You might also like