UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
Assignment 3
JEE - (10%)
JSP, Servlet, DAO, JDBC Full project
example
New requirements:
- add on a registration page with 2 columns
(username, password)
- make sure it is insertable to database when
register as a new user.
Before start, if you open Oracle XE and encounter error msg like this, means your Oracle Services is
stopped,
You must restart it.
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
Run the [Link] and choose Oracle XE and start it.
Sometimes, when you open Eclipse and restart Server of the Dynamic Web
Project, but encounter this msg(8080 in used why?, how to solve it?
Go to open Resource Monitor in RUN, to check port 8080 is used by who….
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
From here, we know that port 8080 being used my Listerner Oracle TNSLSNR
Another issue: Image above shown Listerner XE being used.
private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:xe";
OR Maybe you thought is Server being restarted, so you try to go Tomcat start the server again.
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
Then go to Eclipse Restart the server again, but now the error message is different.
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
So actually the best way to solve this problem is :
Change the tomcat server PORT To another…such as 8082….
How to change?
DONE….
JSP: The process flow
This diagram basically shows the process flow in our application
1. The user enters his username and password in the fields displayed by the JSP - [Link] -
2. When the user submits, the servlet responsible for handling the request is called -
LoginServlet -
3. The Servlet is responsible for calling the appropriate method in the DAO so that it can
indirectly interact with the DB.
It is also responsible for setting and updating data saved in the bean, which will be used later
by the DAO.
In our application,
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
o The LoginServlet creates a new instant of the UserBean and fills it with the username
and the password entered by the user. The DAO will use this bean later to compare
between the user input and the DB data
o The Servlet calls the "login" method in the "UserDAO" to start performing its task
4. The Login method, in the DAO, is responsible for checking whether the data entered by the
user exists in the DB or not.
In addition, it has to update the Bean's data that will be used later by the servlet.
In our application,
o The DAO uses the ConnectionManager class to get the DB connection
o Query the DB (asks the DB to search for a user having certain username and
password ) and checks,
▪ If the ResultSet is empty, this means that the username and password were
invalid (not in the DB).
▪ If the ResultSet is not empty, this means that the username and password
were valid.
o Updates the UserBean.
▪ In case of valid username and password, the DAO fills the bean with the rest
of the user's information that will need to be displayed later by the JSP (first
and last names).
In addition, it sets the "valid" attribute of the bean to true.
▪ Otherwise, the DAO sets the "valid" attribute of the bean to false
Now we know if the user was registered or not
5. Finally, the Servlet will check the validity of the user (by reading the valid attribute of the
bean) and redirect to the appropriate JSP .
o If valid, the servlet will
▪ Add the bean as an attribute to the session. The bean will be used by the JSP
to display the user's first and last names
▪ Redirect to [Link]- That will welcome the user
o If invalid, the servlet will redirect to [Link]- That will ask the user to sign
up
JSP - Servlets: Full Login Example
Example's Implementation Steps
As mentioned in the application description, the user will have to enter his username and password, so
first of all, we need a JSP that asks the user to input his username and password in their corresponding
fields.
No 1. To have this JSP, please follow these steps:
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
Open eclipse
Create a new "Dynamic Web Project"
Name it "LoginExampleProject"
Create the JSP
In the "Web Content" folder, create a new JSP
Name it "[Link]"
Place this code
<%@ page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Login Page</title>
</head>
<body>
<form action="login">
Please enter your username
<input type="text" name="un"/><br>
Please enter your password
<input type="text" name="pw"/>
<input type="submit" value="submit">
</form>
</body>
</html>
As you can see; (in the LoginPage which is [Link]) when the user submits, the JSP calls
"LoginServlet".This LoginServlet is intended to handle the Business logic associated with the request.
No2. Create the LoginServlet by following these steps:
In the "src" folder, create a new "Package"
Name it "[Link]"
In the "[Link]", create a new "Servlet"
Name it "LoginServlet"
Place this code
package [Link];
import [Link];
import [Link];
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
import [Link];
import [Link];
import [Link];
import [Link];
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, [Link] {
try {
UserBean user = new UserBean();
[Link]([Link]("un"));
[Link]([Link]("pw"));
user = [Link](user);
if ([Link]()) {
HttpSession session = [Link](true);
[Link]("currentSessionUser", user);
[Link]("[Link]"); // logged-in page
}
else
[Link]("[Link]"); // error page
}
catch (Throwable theException) {
[Link](theException);
}
}
}
The login servlet instantiates a Bean that is of type "UserBean", and then calls the DAO named
"UserDAO".
Our UserBean is a class representing the User table in our Database (where each column in the user table
has a corresponding instance variable with a setter and a getter method).
The DAO, as said before, contains methods needed to communicate with the data source. In our example,
the only needed method is the login method that checks if the username and password inputted by the
user are valid or not.
Before implementing the DAO, you need to prepare your Data Source.
Create a table in your DB (named table as myuser)
Create table myuser
(
firstname varchar2(20),
lastname varchar2(20),
username varchar2(20),
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
password varchar2(20)
);
Insert 3 users;
insert into myuser values ("Raymond", "Chew", "ray", "1234");
insert into myuser values ("Mohammad", "Ali", "ali", "1234");
insert into myuser values ("James", "Bond", "james", "1234");
Name it myuser
Create the columns: 'FirstName', 'LastName', 'username', and 'password'
Refer to your DB as a data source from "Administrative tools" in Control Panel
Please follow these steps to implement the Bean and the DAO
No3. Create the "UserBean" class
In the " [Link] ", create a new "Class"
Name it "UserBean"
Place this code
package [Link];
public class UserBean {
private String username;
private String password;
private String firstName;
private String lastName;
public boolean valid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String newLastName) {
lastName = newLastName;
}
public String getPassword() {
return password;
}
public void setPassword(String newPassword) {
password = newPassword;
}
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
public String getUsername() {
return username;
}
public void setUserName(String newUsername) {
username = newUsername;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean newValid) {
valid = newValid;
}
}
JSP - Servlets: Full Login Example
No4. Create the "UserDAO" class
In the " [Link] ", create a new "Class"
Name it "UserDAO"
Place this code
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class UserDAO {
static Connection currentCon = null;
static ResultSet rs = null;
public static UserBean login(UserBean bean) {
// preparing some objects for connection
[Link]("JIJIJI");
Statement stmt = null;
String username = [Link]();
String password = [Link]();
String searchQuery = "select * from myuser where username='" + username + "'
AND password='" + password + "'";
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
// "[Link]" prints in the console; Normally used to trace the
process
[Link]("Your user name is " + username);
[Link]("Your password is " + password);
[Link]("Query: " + searchQuery);
try {
// connect to DB
currentCon = [Link]();
stmt = [Link]();
rs = [Link](searchQuery);
boolean more = [Link]();
// if user does not exist set the isValid variable to false
if (!more) {
[Link]("Sorry, you are not a registered user! Please sign
up first");
[Link](false);
}
// if user exists set the isValid variable to true
else if (more) {
String firstName = [Link]("FirstName");
String lastName = [Link]("LastName");
[Link]("Welcome " + firstName);
[Link](firstName);
[Link](lastName);
[Link](true);
}
}
catch (Exception ex) {
[Link]("Log In failed: An Exception has occurred! " + ex);
}
// some exception handling
finally {
if (rs != null) {
try {
[Link]();
} catch (Exception e) {
}
rs = null;
}
if (stmt != null) {
try {
[Link]();
} catch (Exception e) {
}
stmt = null;
}
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
if (currentCon != null) {
try {
[Link]();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
}
The DAO uses a class named "ConnectionManager" to get a connection with the DB.
No5. Create the "ConnectionManager" class:
In the " [Link] ", create a new "Class"
Name it "ConnectionManager"
Place this code
package [Link];
import [Link].*;
import [Link].*;
public class ConnectionManager {
static Connection con;
private static final String DB_DRIVER = "[Link]";
private static final String DB_CONNECTION =
"jdbc:oracle:thin:@localhost:1521:xe";
private static final String DB_USER = "SYSTEM";
private static final String DB_PASSWORD = "1234";
public static Connection getConnection() {
try {
[Link]("connected222");
[Link](DB_DRIVER);
[Link]("connected333");
try {
con = [Link](DB_CONNECTION,DB_USER,DB_PASSWORD);
[Link]("connected");
}
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
catch (SQLException ex) {
[Link]();
}
}
catch (ClassNotFoundException e) {
[Link](e);
}
return con;
}
}
JSP - Servlets: Full Login Example
Finally, we are done with the logic and accessing the DB. So back to the interface, we need two JSPs; one
for the valid login and another for the invalid. The two JSPs are
• [Link]: Displays a message to welcome the user, using his first and last names (retrieved from
the DB)
• [Link]: Displays a message to inform the user that he is not a registered user
No.6. Steps to create the [Link] (After login successfully from [Link])
In the "WebContent" folder, create a new "JSP"
Name it "[Link]"
Place this code
<%@ page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
import="[Link]" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<meta http-equiv="Content-Type"
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
content="text/html; charset=windows-1256">
<title> User Logged Successfully </title>
</head>
<body>
<center>
<%
UserBean currentUser = (UserBean) [Link]("currentSessionUser");
%>
Welcome <%= [Link]() + " " + [Link]() %>
</center>
</body>
</html>
No7. Steps to create the "invalidLogin" JSP
In the "WebContent" folder, create a new "JSP"
Name it "[Link]"
Place this code
<%@ page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=windows-1256">
<title>Invalid Login</title>
</head>
<body>
<center>
Sorry, you are not a registered user! Please sign up first
</center>
</body>
</html>
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)
Run the application, If you do not know any of the following steps, please check Steps 5-8 in
the JSP Example
Set [Link] to be your Home page (from [Link])
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link] id="WebApp_ID" version="3.0">
<display-name>myapp</display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
</web-app>
Add your Project to Tomcat
Start Tomcat
Go to [Link]
Test your project
This should be the result
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)