0% found this document useful (0 votes)
24 views

Session - 1 Forms and Session Management

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Session - 1 Forms and Session Management

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Presents

Forms and Session management

ICT Academy 1
Registration Form using JSP + Servlet :

Below diagram shows the Employee Registration JSP page:

• Let me list out the tools and technologies that I have used to develop
this application.
ICT Academy 2
Tools and technologies used

• JSP - 2.2 +
• IDE - STS/Eclipse Neon.3
• JDK - 1.8 or later
• Apache Tomcat - 8.5
• JSTL - 1.2.1
• Servlet API - 2.5
• MySQL - mysql-connector-java-8.0.13.jar

ICT Academy 3
Development Steps

• Create an Eclipse Dynamic Web Project


• Add Dependencies
• Project Structure
• MySQL Database Setup
• Create a JavaBean - Employee.java
• Create a EmployeeDao.java
• Create a EmployeeServlet.java
• Create a employeeregister.jsp
• Create a employeedetail.jsp
• Demo
ICT Academy 4
Create an Eclipse Dynamic Web Project
• To create a new dynamic Web project in Eclipse:
• On the main menu select File > New > Project....
• In the upcoming wizard choose Web > Dynamic Web Project.

• Click Next.
• Enter project name as "jsp-servlet-jdbc-mysql-example";
• Make sure that the target runtime is set to Apache Tomcat with the currently
supportedICTversion.
Academy 5
Add Dependencies

Add the latest release of below jar files to the lib folder.

• jsp-api.2.3.1.jar

• servlet-api.2.3.jar

• mysql-connector-java-8.0.13.jar

• jstl-1.2.jar

ICT Academy 6
Project Structure
• Standard project structure for your reference -

ICT Academy 7
MySQL Database Setup
Let's create a database named "employees" in MySQL. Now, let's create
an employee table using below DDL script:

CREATE TABLE `employee` (


`id` int(3) NOT NULL AUTO_INCREMENT,
`first_name` varchar(20) DEFAULT NULL,
`last_name` varchar(20) DEFAULT NULL,
`username` varchar(250) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
`contact` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci;
ICT Academy 8
Create a JavaBean - Employee.java
Let's create an Employee JavaBean class which we will use in JSP action tags.

package net.javaguides.jsp.jdbc.bean;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1 L;
private String firstName;
private String lastName;
private String username;
private String password;
private String address;
private String contact;
public String getFirstName() {
return firstName;
}
ICT Academy 9
Create an EmployeeDao.java
• Let's create EmployeeDao class which contains JDBC code to connect
with MySQL database. Add the following code to n EmployeeDao class:

package net.javaguides.jsp.jdbc.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import net.javaguides.jsp.jdbc.bean.Employee;

ICT Academy 10
Create an EmployeeDao.java

public class EmployeeDao {


public int registerEmployee(Employee employee) throws
ClassNotFoundException {
String INSERT_USERS_SQL = "INSERT INTO employee" +
" (id, first_name, last_name, username, password, address, contact)
VALUES " +
" (?, ?, ?, ?, ?,?,?);";
int result = 0;
Class.forName("com.mysql.jdbc.Driver");
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/employees?useSSL=false", "root",
"root");
ICT Academy 11
PreparedStatement preparedStatement =
connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, employee.getFirstName());
preparedStatement.setString(3, employee.getLastName());
preparedStatement.setString(4, employee.getUsername());
preparedStatement.setString(5, employee.getPassword());
preparedStatement.setString(6, employee.getAddress());
preparedStatement.setString(7, employee.getContact());

System.out.println(preparedStatement);

ICT Academy 12
result = preparedStatement.executeUpdate();

} catch (SQLException e) {
// process sql exception
printSQLException(e);
}
return result;
}

private void printSQLException(SQLException ex) {


for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
ICT Academy 13
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException)
e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
} ICT Academy 14
Create an EmployeeServlet.java
Let's create an EmployeeServlet class to process HTTP request parameters and
redirect to the appropriate JSP page after request data stored in the database:
package net.javaguides.employeemanagement.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.javaguides.employeemanagement.dao.EmployeeDao;
import net.javaguides.employeemanagement.model.Employee;
ICT Academy 15
Create an EmployeeServlet.java

@WebServlet("/register")
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
private EmployeeDao employeeDao;

public void init() {


employeeDao = new EmployeeDao();
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException,
ICT Academy IOException { 16
Create an EmployeeServlet.java

String firstName = request.getParameter("firstName");


String lastName = request.getParameter("lastName");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");

ICT Academy 17
Create an EmployeeServlet.java

Employee employee = new Employee();


employee.setFirstName(firstName);
employee.setLastName(lastName);
employee.setUsername(username);
employee.setPassword(password);
employee.setContact(contact);
employee.setAddress(address);

ICT Academy 18
Create an EmployeeServlet.java
try {
employeeDao.registerEmployee(employee);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

response.sendRedirect("employeedetails.jsp");
}
ICT Academy 19
Create a employeeregister.jsp

Let's design employee registration HTML form with the following fields:

• firstName
• lastName
• username
• password
• address
• contact
ICT Academy 20
Create a employeeregister.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<h1>Employee Register Form</h1>
<form action="<%= request.getContextPath() %>/register" method="post">
<table style="with: 80%">
<tr> ICT Academy 21
Create a employeeregister.jsp
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>UserName</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr> ICT Academy 22
Create a employeeregister.jsp

<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type="text" name="contact" /></td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html> ICT Academy 23
Create an employeedetails.jsp
• After an employee successfully registered then this page show a successful
message on screen:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@page import="net.javaguides.employeemanagement.dao.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head> ICT Academy 24
Create an employeedetails.jsp

<body>
<h1>User successfully registered!</h1>
</body>
</html>

• Note that in the above page, we have used JSP action tags. Read more
about action tags here

ICT Academy 25
Demo

• It's time to see a demo of the above development.

• Deploy this web application in tomcat server.

Employee Registration

• Once you deploy this application successfully

ICT Academy 26
Registration Success Page :

ICT Academy 27
Introduction to Servlet Session Management

• Servlet Session Management is a mechanism in Java used by Web


container to store session information.

• Session tracking is a way to manage the data of a user, this is known


as session management in servlet.

• Session in Java are managed through different ways, such as,


HTTP Session API, Cookies, URL rewriting, etc.

ICT Academy 28
Session Management/ Tracking Methods

User Authorization: It is one way where user provides Username


and password or any authentication credentials from login and then
these are passed via server and client to maintain the servlet session.

URL rewriting: User can append session identifier parameter with


every request and response to keep track of session.

Hidden Fields: User has access to create unique field in HTML


which is hidden, when user starts navigating, user will be able to set
the value uniquely to customer and have track over the session

ICT Academy 29
Session Management/ Tracking Methods

Session Tracking API: It is built on top of all other Tracking


methods. This type of session tracking is used for developers to
minimize overhead of session tracking. Major disadvantage is that most
of the time, user need not have to track session, but need to store some
data in the session that can be used in future requests.

Cookies: Cookie is a key value pair of information sent by server to


browsers. It is the most used technology for session tracking. Cookie is
a smallest piece of information sent by the web server in head tag and is
stored as browser cookie.

ICT Academy 30
Two types in Cookies:

Non-persistent Cookie: It is valid only for single session and is


removed each time when browser gets closed.

Persistent Cookie: It is valid for multiple sessions and is removed


only when user logs out but not when browsers get closed.

HTTP and SSL: Browsers that support Secure Socket Layer


communication use SSL support via HTTPS to generate unique session
key as part of encrypted conversation. Modern sites like e-commerce,
ticket booking, Internet banking, etc., use HTTPs to securely transfer
data and manage session.
ICT Academy 31
Key Method Used in HTTPSession

isNew(): Returns true is user does not know about the session. If
cookies are disabled, then session is new.
getId(): Returns string that contains unique identifier that is assigned to
this session. Is used while using URL rewriting the session.
getAttribute(): Returns the object bound in present session.
setAttribute(): Binds object to present session, uses specified name.
invalidate(): Expires current session and unbinds the object binded
setMaxInactiveInterval(): Specifies time between client requests
before servlet invalidates session. Negative time indicates session
shouldn’t timeout.
ICT Academy 32

You might also like