0% found this document useful (0 votes)
27 views10 pages

Unit4 Webtechnology

The document outlines a servlet and JSF application for user authentication with database connectivity and session tracking. It includes code for login, dashboard, and logout functionalities, as well as database setup instructions. The application ensures that only logged-in users can access the dashboard and provides a mechanism for users to log out, invalidating their session.

Uploaded by

dineshraju3435
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views10 pages

Unit4 Webtechnology

The document outlines a servlet and JSF application for user authentication with database connectivity and session tracking. It includes code for login, dashboard, and logout functionalities, as well as database setup instructions. The application ensures that only logged-in users can access the dashboard and provides a mechanism for users to log out, invalidating their session.

Uploaded by

dineshraju3435
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

UNIT 4

Gadiraju Dinesh

2022115094

SUGGESTED ACTIVITY 1:

servlet programming with database connectivity and session tracking

1) The user logs in using their credentials.

2) If the credentials are valid, the user is redirected to a dashboard page.

3) Session tracking ensures only logged-in users can access the dashboard.

Database Setup

CREATE DATABASE servlet_demo;

USE servlet_demo;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) NOT NULL,

password VARCHAR(50) NOT NULL

);

INSERT INTO users (username, password) VALUES

('admin', 'password123'),

('user', 'userpass');
Servlet Code

1. LoginServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


private static final String DB_URL = "jdbc:mysql://localhost:3306/servlet_demo";
private static final String DB_USER = "root";
private static final String DB_PASS = "password";

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);

String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();

if (rs.next()) {
// Valid user, create session
HttpSession session = request.getSession();
session.setAttribute("username", username);

// Redirect to Dashboard
response.sendRedirect("dashboard");
} else {
out.println("<h3>Invalid username or password!</h3>");
out.println("<a href='login.html'>Try Again</a>");
}

stmt.close();
conn.close();
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
}
}
}
2. DashboardServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class DashboardServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

HttpSession session = request.getSession(false); // Don't create a new session

response.setContentType("text/html");

PrintWriter out = response.getWriter();

if (session != null && session.getAttribute("username") != null) {

String username = (String) session.getAttribute("username");

out.println("<h2>Welcome, " + username + "!</h2>");

out.println("<a href='logout'>Logout</a>");

} else {

response.sendRedirect("login.html");

3) LogoutServlet.java :

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LogoutServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
HttpSession session = request.getSession(false);

if (session != null) {

session.invalidate(); // Invalidate session

response.sendRedirect("login.html");

Login.html

<!DOCTYPE html>

<html>

<head>

<title>Login</title>

</head>

<body>

<h2>Login</h2>

<form action="login" method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br><br>

<button type="submit">Login</button>

</form>

</body>

</html>

Web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">

<servlet>

<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>/login</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>DashboardServlet</servlet-name>

<servlet-class>DashboardServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>DashboardServlet</servlet-name>

<url-pattern>/dashboard</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>LogoutServlet</servlet-name>

<servlet-class>LogoutServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LogoutServlet</servlet-name>

<url-pattern>/logout</url-pattern>

</servlet-mapping>

</web-app>
SUGGESTED ACTIVITY 2:

1) Users log in with a username and password.

2) The database validates the credentials.

3) If successful, a session is created, and the user is redirected to a dashboard.

4) The session is tracked to ensure only logged-in users access the dashboard.

5) Users can log out to end the session.

Database Setup:

CREATE DATABASE jsf_demo;

USE jsf_demo;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) NOT NULL,

password VARCHAR(50) NOT NULL

);

INSERT INTO users (username, password) VALUES

('admin', 'password123'),

('user', 'userpass');

JSF Application

1. Managed Bean (LoginBean.java)

import java.io.Serializable;

import java.sql.*;
import javax.faces.bean.ManagedBean;

import javax.faces.bean.SessionScoped;

import javax.faces.context.FacesContext;

@ManagedBean

@SessionScoped

public class LoginBean implements Serializable {

private String username;

private String password;

private boolean loggedIn = false;

private static final String DB_URL = "jdbc:mysql://localhost:3306/jsf_demo";

private static final String DB_USER = "root";

private static final String DB_PASS = "password";

public String getUsername() {

return username;

public void setUsername(String username) {

this.username = username;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

}
public boolean isLoggedIn() {

return loggedIn;

public String login() {

try {

Class.forName("com.mysql.cj.jdbc.Driver");

Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);

String query = "SELECT * FROM users WHERE username = ? AND password = ?";

PreparedStatement stmt = conn.prepareStatement(query);

stmt.setString(1, username);

stmt.setString(2, password);

ResultSet rs = stmt.executeQuery();

if (rs.next()) {

loggedIn = true;

return "dashboard?faces-redirect=true"; // Redirect to dashboard.xhtml

} else {

FacesContext.getCurrentInstance().addMessage(null,

new javax.faces.application.FacesMessage("Invalid username or password"));

return "login";

} catch (Exception e) {

e.printStackTrace();

return "login";

public String logout() {

loggedIn = false;
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

return "login?faces-redirect=true";

Login Page (login.xhtml)

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:h="http://xmlns.jcp.org/jsf/html">

<h:head>

<title>Login</title>

</h:head>

<h:body>

<h2>Login</h2>

<h:form>

<h:outputLabel for="username" value="Username:" />

<h:inputText id="username" value="#{loginBean.username}" required="true" /><br /><br />

<h:outputLabel for="password" value="Password:" />

<h:inputSecret id="password" value="#{loginBean.password}" required="true" /><br


/><br />

<h:commandButton value="Login" action="#{loginBean.login}" />

</h:form>

</h:body>

</html>

Dashboard Page (dashboard.xhtml)

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>

<title>Dashboard</title>

</h:head>

<h:body>

<h2>Welcome, #{loginBean.username}!</h2>

<h:form>

<h:commandButton value="Logout" action="#{loginBean.logout}" />

</h:form>

</h:body>

</html>

Web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">

<servlet>

<servlet-name>FacesServlet</servlet-name>

<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>FacesServlet</servlet-name>

<url-pattern>*.xhtml</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>login.xhtml</welcome-file>

</welcome-file-list>

</web-app>

You might also like