SlideShare a Scribd company logo
3 tier Architecture -
JSP Project Module
1
How to create a Web Project in Eclipse
2
3
4
5
6
7
8
9
10
Tasks
• Complete the classes with methods by dividing them
into sub-tasks.
Example:
Module- Customer registration
Classes-view, service, DB, Customer bean
Methods-
• saveDetails()-return value Customer id
• fetchDetails(custID) - return Customer details object
• Show the return customer id or error message in a
page
11
Package
Packages are nothing more than the way we organize files
into different directories according to their functionality,
usability as well as category they should belong to.
12
13
14
Add a jsp page to WebContent for
Registering an Employee
15
Creating a bean for passing employee
details
16
Define required variables
17
Generating Getters and Setters
18
19
Creating a Service layer
20
21
22
• You have to import classes EmployeeBean, DB.AddEmployee
since service layer deals with database layer and bean class.
• Code for service layer is:
import com.baabtra.bean.EmployeeBean;
import com.baabtra.DB.AddEmployee;
public class AddEmployeeService {
public String registerEmployee(EmployeeBean emp)
{
AddEmployee register= new AddEmployee();
String returnmsg=register.registerEmployeeDB(emp);
return returnmsg;
}
}
23
Presentation layer
• Post data to page register.jsp
• Import required classes to register.jsp
<%@ page import="com.Pharma.bean.EmployeeBean"%>
<%@ page import="com.Pharma.Service.AddEmployeeService"%>
• Store data in variables
<%
String employee_id =request.getParameter("employee_id");
System.out.println("Employee Id :"+employee_id);
String employee_name =request.getParameter("employee_name");
String user_name =request.getParameter("user_name");
String employee_password =request.getParameter("employee_password");
String address =request.getParameter("address");
String gender=request.getParameter("gender");
String dob =(String)request.getParameter("txt_dob");
%>
24
• Create object form employee bean and set
values for its properties
<%
EmployeeBean emp=new EmployeeBean();
emp.setEmpId(employee_id);
emp.setEmpName(employee_name);
emp.setUserName(user_name);
emp.setPaassword(employee_password);
emp.setAddress(address);
emp.setGender(gender);
emp.setDob(dob1);
emp.setDoj(doj1);
%>
25
• Create object for service class and call the
method for registering the employee
<%
AddEmployeeService add= new AddEmployeeService();
String result= add.registerEmployee(emp);
%>
• Check the result and do the necessary action
if (result.equals("Success")){.
//Redirect to page for success
response.sendRedirect("Employee.jsp");
}
else{
out.println("Data not saved");
}
%>
26
Task-How to connect to DB?
27
JDBC
• The JDBC (Java Database Connectivity) API helps a Java
program to access a database in a standard way
• JDBC is a specification that specifies two things
1. tells the database vendors how to write a driver program to
interface Java programs with their database
2. tells the programmers how to write a Java program to access any
database
• A Driver written according to this standard is
called the JDBC Driver
• All related classes and interfaces are present
in the java.sql package
28
• The steps involved in a database interaction
are:
– Loading the specific driver(there are different
drivers for different DB)
– Making a connection to the database using the
predefined methods in the java.sql package
– Sending and executing SQL statements to the
database
– Processing the results
29
Step1: Load the database Driver
• Load the driver class by calling Class.forName()
with the Driver class name as an argument.
• Once loaded, the Driver class creates an instance
of itself in the memory from which it is then used
• The General format is :
Class.forName( String ClassName );
• Example :
Class.forName ("com.mysql.jdbc.Driver");
30
Step2: Setting Connection using Driver
Manager class
– Driver Manager Manages all the JDBC Drivers that
are loaded in the memory
– Its getConnection() method is used to establish a
connection to a database.
– It uses a username, password, and a jdbc url to
establish a connection to the database and returns
a connection object.
Connection connection
=DriverManager.getConnection (url , username,
password);
31
Connection conn =null;
String username = "root";
String password = "";
String url = "jdbc:mysql://localhost/project";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url,
userName, password);
DB ip
address Database
name
32
Step3:Create a Statement object
• After a connection is obtained we can interact with the
database.
• We use methods defined in Connection interface for
interacting with the database via the established
connection.
• To execute SQL statements, we need to instantiate a
Statement object from the connection object by using
the createStatement() method.
Statement statement = connection.createStatement();
• A statement object is used to send and execute SQL
statements to a database.
33
Statement interface
• Defines methods that are used to interact with database via the execution
of SQL statements.
• The different methods are:
– executeQuery(String query) - executes an SQL statement (SELECT) that
queries a database and returns a ResultSet object.
– getResultSet() - used to retrieve the ResultSet object
– executeUpdate(String query) - executes an SQL statement (INSERT ,UPDATE
or DELETE) that updates the database and returns an integer value which
specifies the number of rows modified
– execute(String query) - executes an SQL statement that is written as String
object
34
ResultSet Interface
• Maintains a pointer to a row within the tabular results obtained .
• The next() method is used to iterate through the rows of the tabular
results. Initially the iterator is initialized to a position before the first row.
Hence we have to call next() once to move it to the first row.
• The different methods are:
– getBoolean(int) - Get the value of a column in the current row as a Java
boolean.
– getDouble(int) - Get the value of a column in the current row as a Java
double.
– getInt(int) - Get the value of a column in the current row as a Java int.
– getString(String)-Get value as java string
35
Database connection class
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
public class
{//declare connection as instance variable
public Connection conn;
public Dbconnection()
{ //constructor for the class
String url="jdbc:mysql://localhost:3306/";
String dbname=“database_name";
String driver="com.mysql.jdbc.Driver";
String dbusername="root";
String dbpassword="baabtra";
try {
Class.forName(driver).newInstance();
conn=(DriverManager.getConnection(url+dbname,dbusername,dbpassword);
System.out.println("connected......");
} catch (Exception e) {
System.out.println(e.getMessage()); 36
Creating DB layer
• Create a method inside AddEmployee class
public String registerEmployeeDB(EmployeeBean emp)
{
}
• Strip the object ‘emp’ to get values and store it in
variables
String employee_id=emp.getEmpId();
String employee_name=emp.getEmpName();
String user_name=emp.getUserName();
String employee_password=emp.getPaassword();
String address=emp.getAddress();
String gender=emp.getGender();
String dob=emp.getDob();
String doj=emp.getDoj();
37
Add try catch block
try{
Connection conn=dbconnection.conn;
Statement st=(Statement) conn.createStatement();
try{
Statement st= (Statement) conn.createStatement();
//your logic here
}
catch (Exception e) {
System.out.println(e);
}
catch (Exception e) {
System.out.println(e);
e.printStackTrace
}
Finally{
conn.close()
} } 38
Do the database operation for
registering the employee
//insert data into login table
String sqlQuery ="insert into tbl_login(user_name, password,role)"+
"values('"+user_name+"',
'"+employee_password+"','EMPLOY')";
int Count=st.executeUpdate(sqlQuery) ;
//Check whether data is inserted or not
if (Count>0)
{
int id=0;
//select currently inserted id (auto increment )from login table
ResultSet rs=st.executeQuery("select max(pk_login_id) as id from
tbl_login ");
while(rs.next()){
id=rs.getInt("id");
}
39
//Insert data to employee table
sqlQuery="insert into
tbl_employe(pk_employee,fk_loginid,emp_first_name,emp_addres, "+
"emp_gender,emp_dob,emp_doj) values('"+employee_id+"',"+
id+",'"+employee_name+"','"+
address+"','"+gender+"','"+dob+"','"+doj+"')";
int Count1=st.executeUpdate(sqlQuery);
//Return success or fail depending on status of database operation
if (Count1>0){
return "Success";
}}
else
{
return "Fail";
}
40
Selecting and displaying data from
database using list
• Create method for getting data in database
layer
public List getEmployeeListDB(){
//code for connecting to database
//declarea list of Employee bean
//do the database operation (select data from database)
//store the result set in the list
//pass it to service layer
}
41
//Declare list of employee bean
List<EmployeeBean > details=new ArrayList<EmployeeBean >();
ResultSet rs=s.executeQuery("Select * from employees");
//loop to fetch the query results one by one
while(rs.next()){
//ceating object to save each row details
EmployeeBean emp=new CustomerBean();
emp.setName(rs.getString("name"));
emp.setAddress(rs.getString("address"));
emp.setEmail(rs.getString("email"));
//adding the objects to the list object that was made
details.add(emp);
}
conn.close();
//returning the list with objects
return details;
42
Code in service class
import java.util.List;
import com.babte.DB.Employee;
public class EmployeeService {
public List getEmployeeListService()
{
EmployeeDB ObjEmp=new EmployeeDB();
List list=ObjEmp. getEmployeeListDB();
return list;
}
}
43
Code in JSP
<%@page import="com.babate.service.EmployeeService"%>
<%@page import="java.util.List"%>
<%@page import="com.babte.Bean.EmployeeBean"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Employee Details
<table border="1“>
<tr>
<td>Sl No</td>
<td>Name</td>
<td>Address</td>
<td>Email</td>
</tr>
44
<%
EmployeeService service=new EmployeeService ();
List details= service. getEmployeeListService();
for(int i=0;i<details.size();i++)
{
EmployeeBean emp =(EmployeeBean )details.get(i);
String name= emp.getName();
String address= emp.getAddress();
String email= emp.getEmail();
%>
<tr>
<td><%=i+1%></td>
<td><%=name%></td>
<td><%=address%></td>
<td><%=email%></td>
</tr>
<%} %>
</table>
</body>
</html>
45
End of day
If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

More Related Content

What's hot

JDK1.6
JDK1.6JDK1.6
JDK1.6
india_mani
 
Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)
Trisha Gee
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
Knoldus Inc.
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
Allan Huang
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
Ivelin Yanev
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
Jussi Pohjolainen
 
Tech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM WorkflowsTech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM Workflows
51 lecture
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
CodeOps Technologies LLP
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Adil Mehmoood
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
vishal choudhary
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
phanleson
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
nartamonov
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
JavaEE Trainers
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
Nuha Noor
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2
Vinaykumar Hebballi
 
Java RMI
Java RMIJava RMI
Java RMI
Sunil OS
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
Simon Ritter
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
kshanth2101
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 

What's hot (20)

JDK1.6
JDK1.6JDK1.6
JDK1.6
 
Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Tech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM WorkflowsTech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM Workflows
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2
 
Java RMI
Java RMIJava RMI
Java RMI
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 

Similar to Jsp project module

Jdbc
JdbcJdbc
Jdbc
lathasiva
 
22jdbc
22jdbc22jdbc
22jdbc
Adil Jafri
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Java JDBC
Java JDBCJava JDBC
Jdbc
JdbcJdbc
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
KV(AFS) Utarlai, Barmer (Rajasthan)
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 
JDBC
JDBCJDBC
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
Soham Sengupta
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
chhaichivon
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
IMC Institute
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
arikazukito
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Atul Saurabh
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
AISHWARIYA1S
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
nrjoshiee
 

Similar to Jsp project module (20)

Jdbc
JdbcJdbc
Jdbc
 
22jdbc
22jdbc22jdbc
22jdbc
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
JDBC
JDBCJDBC
JDBC
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 

More from baabtra.com - No. 1 supplier of quality freshers

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
Best coding practices
Best coding practicesBest coding practices
Core java - baabtra
Core java - baabtraCore java - baabtra
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php database connectivity
Php database connectivityPhp database connectivity
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Blue brain
Blue brainBlue brain
5g
5g5g
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Gd baabtra
Gd baabtraGd baabtra

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Recently uploaded

Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 

Recently uploaded (20)

Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 

Jsp project module

  • 1. 3 tier Architecture - JSP Project Module 1
  • 2. How to create a Web Project in Eclipse 2
  • 3. 3
  • 4. 4
  • 5. 5
  • 6. 6
  • 7. 7
  • 8. 8
  • 9. 9
  • 10. 10
  • 11. Tasks • Complete the classes with methods by dividing them into sub-tasks. Example: Module- Customer registration Classes-view, service, DB, Customer bean Methods- • saveDetails()-return value Customer id • fetchDetails(custID) - return Customer details object • Show the return customer id or error message in a page 11
  • 12. Package Packages are nothing more than the way we organize files into different directories according to their functionality, usability as well as category they should belong to. 12
  • 13. 13
  • 14. 14
  • 15. Add a jsp page to WebContent for Registering an Employee 15
  • 16. Creating a bean for passing employee details 16
  • 19. 19
  • 20. Creating a Service layer 20
  • 21. 21
  • 22. 22
  • 23. • You have to import classes EmployeeBean, DB.AddEmployee since service layer deals with database layer and bean class. • Code for service layer is: import com.baabtra.bean.EmployeeBean; import com.baabtra.DB.AddEmployee; public class AddEmployeeService { public String registerEmployee(EmployeeBean emp) { AddEmployee register= new AddEmployee(); String returnmsg=register.registerEmployeeDB(emp); return returnmsg; } } 23
  • 24. Presentation layer • Post data to page register.jsp • Import required classes to register.jsp <%@ page import="com.Pharma.bean.EmployeeBean"%> <%@ page import="com.Pharma.Service.AddEmployeeService"%> • Store data in variables <% String employee_id =request.getParameter("employee_id"); System.out.println("Employee Id :"+employee_id); String employee_name =request.getParameter("employee_name"); String user_name =request.getParameter("user_name"); String employee_password =request.getParameter("employee_password"); String address =request.getParameter("address"); String gender=request.getParameter("gender"); String dob =(String)request.getParameter("txt_dob"); %> 24
  • 25. • Create object form employee bean and set values for its properties <% EmployeeBean emp=new EmployeeBean(); emp.setEmpId(employee_id); emp.setEmpName(employee_name); emp.setUserName(user_name); emp.setPaassword(employee_password); emp.setAddress(address); emp.setGender(gender); emp.setDob(dob1); emp.setDoj(doj1); %> 25
  • 26. • Create object for service class and call the method for registering the employee <% AddEmployeeService add= new AddEmployeeService(); String result= add.registerEmployee(emp); %> • Check the result and do the necessary action if (result.equals("Success")){. //Redirect to page for success response.sendRedirect("Employee.jsp"); } else{ out.println("Data not saved"); } %> 26
  • 27. Task-How to connect to DB? 27
  • 28. JDBC • The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way • JDBC is a specification that specifies two things 1. tells the database vendors how to write a driver program to interface Java programs with their database 2. tells the programmers how to write a Java program to access any database • A Driver written according to this standard is called the JDBC Driver • All related classes and interfaces are present in the java.sql package 28
  • 29. • The steps involved in a database interaction are: – Loading the specific driver(there are different drivers for different DB) – Making a connection to the database using the predefined methods in the java.sql package – Sending and executing SQL statements to the database – Processing the results 29
  • 30. Step1: Load the database Driver • Load the driver class by calling Class.forName() with the Driver class name as an argument. • Once loaded, the Driver class creates an instance of itself in the memory from which it is then used • The General format is : Class.forName( String ClassName ); • Example : Class.forName ("com.mysql.jdbc.Driver"); 30
  • 31. Step2: Setting Connection using Driver Manager class – Driver Manager Manages all the JDBC Drivers that are loaded in the memory – Its getConnection() method is used to establish a connection to a database. – It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. Connection connection =DriverManager.getConnection (url , username, password); 31
  • 32. Connection conn =null; String username = "root"; String password = ""; String url = "jdbc:mysql://localhost/project"; Class.forName ("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection (url, userName, password); DB ip address Database name 32
  • 33. Step3:Create a Statement object • After a connection is obtained we can interact with the database. • We use methods defined in Connection interface for interacting with the database via the established connection. • To execute SQL statements, we need to instantiate a Statement object from the connection object by using the createStatement() method. Statement statement = connection.createStatement(); • A statement object is used to send and execute SQL statements to a database. 33
  • 34. Statement interface • Defines methods that are used to interact with database via the execution of SQL statements. • The different methods are: – executeQuery(String query) - executes an SQL statement (SELECT) that queries a database and returns a ResultSet object. – getResultSet() - used to retrieve the ResultSet object – executeUpdate(String query) - executes an SQL statement (INSERT ,UPDATE or DELETE) that updates the database and returns an integer value which specifies the number of rows modified – execute(String query) - executes an SQL statement that is written as String object 34
  • 35. ResultSet Interface • Maintains a pointer to a row within the tabular results obtained . • The next() method is used to iterate through the rows of the tabular results. Initially the iterator is initialized to a position before the first row. Hence we have to call next() once to move it to the first row. • The different methods are: – getBoolean(int) - Get the value of a column in the current row as a Java boolean. – getDouble(int) - Get the value of a column in the current row as a Java double. – getInt(int) - Get the value of a column in the current row as a Java int. – getString(String)-Get value as java string 35
  • 36. Database connection class import java.sql.DriverManager; import com.mysql.jdbc.Connection; public class {//declare connection as instance variable public Connection conn; public Dbconnection() { //constructor for the class String url="jdbc:mysql://localhost:3306/"; String dbname=“database_name"; String driver="com.mysql.jdbc.Driver"; String dbusername="root"; String dbpassword="baabtra"; try { Class.forName(driver).newInstance(); conn=(DriverManager.getConnection(url+dbname,dbusername,dbpassword); System.out.println("connected......"); } catch (Exception e) { System.out.println(e.getMessage()); 36
  • 37. Creating DB layer • Create a method inside AddEmployee class public String registerEmployeeDB(EmployeeBean emp) { } • Strip the object ‘emp’ to get values and store it in variables String employee_id=emp.getEmpId(); String employee_name=emp.getEmpName(); String user_name=emp.getUserName(); String employee_password=emp.getPaassword(); String address=emp.getAddress(); String gender=emp.getGender(); String dob=emp.getDob(); String doj=emp.getDoj(); 37
  • 38. Add try catch block try{ Connection conn=dbconnection.conn; Statement st=(Statement) conn.createStatement(); try{ Statement st= (Statement) conn.createStatement(); //your logic here } catch (Exception e) { System.out.println(e); } catch (Exception e) { System.out.println(e); e.printStackTrace } Finally{ conn.close() } } 38
  • 39. Do the database operation for registering the employee //insert data into login table String sqlQuery ="insert into tbl_login(user_name, password,role)"+ "values('"+user_name+"', '"+employee_password+"','EMPLOY')"; int Count=st.executeUpdate(sqlQuery) ; //Check whether data is inserted or not if (Count>0) { int id=0; //select currently inserted id (auto increment )from login table ResultSet rs=st.executeQuery("select max(pk_login_id) as id from tbl_login "); while(rs.next()){ id=rs.getInt("id"); } 39
  • 40. //Insert data to employee table sqlQuery="insert into tbl_employe(pk_employee,fk_loginid,emp_first_name,emp_addres, "+ "emp_gender,emp_dob,emp_doj) values('"+employee_id+"',"+ id+",'"+employee_name+"','"+ address+"','"+gender+"','"+dob+"','"+doj+"')"; int Count1=st.executeUpdate(sqlQuery); //Return success or fail depending on status of database operation if (Count1>0){ return "Success"; }} else { return "Fail"; } 40
  • 41. Selecting and displaying data from database using list • Create method for getting data in database layer public List getEmployeeListDB(){ //code for connecting to database //declarea list of Employee bean //do the database operation (select data from database) //store the result set in the list //pass it to service layer } 41
  • 42. //Declare list of employee bean List<EmployeeBean > details=new ArrayList<EmployeeBean >(); ResultSet rs=s.executeQuery("Select * from employees"); //loop to fetch the query results one by one while(rs.next()){ //ceating object to save each row details EmployeeBean emp=new CustomerBean(); emp.setName(rs.getString("name")); emp.setAddress(rs.getString("address")); emp.setEmail(rs.getString("email")); //adding the objects to the list object that was made details.add(emp); } conn.close(); //returning the list with objects return details; 42
  • 43. Code in service class import java.util.List; import com.babte.DB.Employee; public class EmployeeService { public List getEmployeeListService() { EmployeeDB ObjEmp=new EmployeeDB(); List list=ObjEmp. getEmployeeListDB(); return list; } } 43
  • 44. Code in JSP <%@page import="com.babate.service.EmployeeService"%> <%@page import="java.util.List"%> <%@page import="com.babte.Bean.EmployeeBean"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> Employee Details <table border="1“> <tr> <td>Sl No</td> <td>Name</td> <td>Address</td> <td>Email</td> </tr> 44
  • 45. <% EmployeeService service=new EmployeeService (); List details= service. getEmployeeListService(); for(int i=0;i<details.size();i++) { EmployeeBean emp =(EmployeeBean )details.get(i); String name= emp.getName(); String address= emp.getAddress(); String email= emp.getEmail(); %> <tr> <td><%=i+1%></td> <td><%=name%></td> <td><%=address%></td> <td><%=email%></td> </tr> <%} %> </table> </body> </html> 45
  • 47. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 48. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: info@baabtra.com