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

CSC444 - Assignment 3

This document provides instructions for Assignment 3 of an Enterprise Java Programming course. It includes: 1) Adding a registration page to an existing project with username and password fields and inserting registered users into a database. 2) Troubleshooting issues with Oracle XE services and port 8080 being in use when restarting servers. 3) An overview of the process flow in the application from the user entering credentials on a JSP to validation with the database via a servlet and DAO.

Uploaded by

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

CSC444 - Assignment 3

This document provides instructions for Assignment 3 of an Enterprise Java Programming course. It includes: 1) Adding a registration page to an existing project with username and password fields and inserting registered users into a database. 2) Troubleshooting issues with Oracle XE services and port 8080 being in use when restarting servers. 3) An overview of the process flow in the application from the user entering credentials on a JSP to validation with the database via a servlet and DAO.

Uploaded by

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

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 Services.msc 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 - index.jsp -
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 home.jsp- That will welcome the user
o If invalid, the servlet will redirect to invalidLogin.jsp- 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 "index.jsp"
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"


"http://www.w3.org/TR/html4/loose.dtd">

<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 index.jsp) 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 "com.example"
In the "com.example", create a new "Servlet"
Name it "LoginServlet"
Place this code

package com.example;

import java.io.IOException;
import javax.servlet.ServletException;
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, java.io.IOException {

try {

UserBean user = new UserBean();


user.setUserName(request.getParameter("un"));
user.setPassword(request.getParameter("pw"));

user = UserDAO.login(user);

if (user.isValid()) {

HttpSession session = request.getSession(true);


session.setAttribute("currentSessionUser", user);
response.sendRedirect("home.jsp"); // logged-in page
}

else
response.sendRedirect("invalidLogin.jsp"); // error page
}

catch (Throwable theException) {


System.out.println(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 " com.example ", create a new "Class"
Name it "UserBean"
Place this code

package com.example;

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 " com.example ", create a new "Class"
Name it "UserDAO"
Place this code

package com.example;

import java.text.*;
import java.util.*;
import java.sql.*;

public class UserDAO {


static Connection currentCon = null;
static ResultSet rs = null;

public static UserBean login(UserBean bean) {

// preparing some objects for connection


System.out.println("JIJIJI");
Statement stmt = null;

String username = bean.getUsername();


String password = bean.getPassword();

String searchQuery = "select * from myuser where username='" + username + "'


AND password='" + password + "'";
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)

// "System.out.println" prints in the console; Normally used to trace the


process
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + searchQuery);

try {
// connect to DB
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();

// if user does not exist set the isValid variable to false


if (!more) {
System.out.println("Sorry, you are not a registered user! Please sign
up first");
bean.setValid(false);
}

// if user exists set the isValid variable to true


else if (more) {
String firstName = rs.getString("FirstName");
String lastName = rs.getString("LastName");

System.out.println("Welcome " + firstName);


bean.setFirstName(firstName);
bean.setLastName(lastName);
bean.setValid(true);
}
}

catch (Exception ex) {


System.out.println("Log In failed: An Exception has occurred! " + ex);
}

// some exception handling


finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
stmt = null;
}
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)

if (currentCon != null) {
try {
currentCon.close();
} 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 " com.example ", create a new "Class"


Name it "ConnectionManager"
Place this code

package com.example;

import java.sql.*;
import java.util.*;

public class ConnectionManager {

static Connection con;

private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";


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 {
System.out.println("connected222");

Class.forName(DB_DRIVER);
System.out.println("connected333");

try {
con = DriverManager.getConnection(DB_CONNECTION,DB_USER,DB_PASSWORD);
System.out.println("connected");

}
UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)

catch (SQLException ex) {


ex.printStackTrace();
}
}

catch (ClassNotFoundException e) {
System.out.println(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

• home.jsp: Displays a message to welcome the user, using his first and last names (retrieved from
the DB)
• invalidLogin.jsp: Displays a message to inform the user that he is not a registered user

No.6. Steps to create the home.jsp (After login successfully from index.jsp)

In the "WebContent" folder, create a new "JSP"


Name it "home.jsp"
Place this code

<%@ page language="java"


contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
import="com.example.UserBean" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<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) session.getAttribute("currentSessionUser");
%>

Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %>


</center>

</body>

</html>

No7. Steps to create the "invalidLogin" JSP


In the "WebContent" folder, create a new "JSP"
Name it "invalidLogin.jsp"
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"


"http://www.w3.org/TR/html4/loose.dtd">

<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 index.jsp to be your Home page (from web.xml)

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>myapp</display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.example.LoginServlet</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 http://Localhost/loginExample
Test your project

This should be the result


UiTM Melaka Kampus Jasin CSC444 Enterprise Java Programming (A3)

You might also like