My code:
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>eBillingGeneratorTool</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>dbUser</param-name>
<param-value>ebgt</param-value>
</context-param>
<context-param>
<param-name>dbPassword</param-name>
<param-value>ebgt123</param-value>
</context-param>
<context-param>
<param-name>dbURL</param-name>
<param-value>
jdbc:mysql://localhost:3306/UserDB</param-value>
</context-param>
<context-param>
<param-name>log4j-config</param-name>
<param-value>WEB-INF/log4j.xml</param-value>
</context-param>
<!-- <error-page>
<error-code>404</error-code>
<location>/AppErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/AppErrorHandler</location>
</error-page>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.ebgt.servlet.filters.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>-->
</web-app>
******************************************************************************************************************************
Log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<appender name="dbexample" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${catalina.home}/logs/dbexample.log"/>
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="20MB" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
</layout>
</appender>
<logger name="com.ebgt" additivity="false">
<level value="DEBUG" />
<appender-ref ref="dbexample"/>
</logger>
<root>
<level value="debug" />
<appender-ref ref="dbexample" />
</root>
</log4j:configuration>
********************************************************************************************************************************************************
LoginServlet.java
package com.ebgt.servlet.login;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import com.ebgt.util.User;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(LoginServlet.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String password = request.getParameter("password");
String errorMsg = null;
if(id == null || id.equals("")){
errorMsg ="User id can't be null or empty";
}
if(password == null || password.equals("")){
errorMsg = "Password can't be null or empty";
}
if(errorMsg != null){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>"+errorMsg+"</font>");
rd.include(request, response);
}else{
Connection con = (Connection) getServletContext().getAttribute("DBConnection");
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("select id, firstname, lastname from Users where id=? and password=? limit 1");
ps.setString(1, id);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs != null && rs.next()){
User user = new User(rs.getString("firstname"), rs.getString("lastname"), rs.getString("id"));
logger.info("User found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("home.jsp");;
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
logger.error("User not found with id="+id);
out.println("<font color=red>No user found with given id, please register first.</font>");
rd.include(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
logger.error("Database connection problem");
throw new ServletException("DB Connection problem.");
}finally{
try {
rs.close();
ps.close();
} catch (SQLException e) {
logger.error("SQLException in closing PreparedStatement or ResultSet");;
}
}
}
}
}
****************************************************************************************************************************************************************************
Logoutservlet.java
package com.ebgt.servlet.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
@WebServlet(name = "Logout", urlPatterns = { "/Logout" })
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(LogoutServlet.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
logger.info("JSESSIONID="+cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
logger.info("User="+session.getAttribute("User"));
if(session != null){
session.invalidate();
}
response.sendRedirect("login.html");
}
}
****************************************************************************************************************************************************************************
Registerservlet.java
package com.ebgt.servlet.login;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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 org.apache.log4j.Logger;
@WebServlet(name = "Register", urlPatterns = { "/Register" })
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(RegisterServlet.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String password = request.getParameter("password");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String errorMsg = null;
if(id == null || id.equals("")){
errorMsg = "ID can't be null or empty.";
}
if(password == null || password.equals("")){
errorMsg = "Password can't be null or empty.";
}
if(firstname == null || firstname.equals("")){
errorMsg = "First Name can't be null or empty.";
}
if(lastname == null || lastname.equals("")){
errorMsg = "Last name can't be null or empty.";
}
if(errorMsg != null){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/register.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>"+errorMsg+"</font>");
rd.include(request, response);
}else{
Connection con = (Connection) getServletContext().getAttribute("DBConnection");
PreparedStatement ps = null;
try {
ps = con.prepareStatement("insert into Users(id,firstname,lastname, password) values (?,?,?,?)");
ps.setString(1, id);
ps.setString(2, firstname);
ps.setString(3, lastname);
ps.setString(4, password);
ps.execute();
logger.info("User registered with ID="+id);
//forward to login page to login
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=green>Registration successful, please login below.</font>");
rd.include(request, response);
} catch (SQLException e) {
e.printStackTrace();
logger.error("Database connection problem");
throw new ServletException("DB Connection problem.");
}finally{
try {
ps.close();
} catch (SQLException e) {
logger.error("SQLException in closing PreparedStatement");
}
}
}
}
}
****************************************************************************************************************************************************************************
DBConnnectionmanager
package com.ebgt.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnectionManager {
private Connection connection;
public DBConnectionManager(String dbURL, String user, String pwd) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(dbURL, user, pwd);
}
public Connection getConnection(){
return this.connection;
}
}
****************************************************************************************************************************************************************************
User.java
package com.ebgt.util;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 6297385302078200511L;
private String firstname;
private String lastname;
private String id;
public User(String fm, String ln,String id){
this.lastname=ln;
this.firstname=fm;
this.id=id;
}
public void setfName(String firstname) {
this.firstname = firstname;
}
public void setlname(String lastname) {
this.lastname = lastname;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString(){
return "firstame="+this.firstname+", lastname="+this.lastname;
}
}
****************************************************************************************************************************************************************************
AppErrorHandler.java
package com.ebgt.servlet.errorhandler;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AppErrorHandler extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>Exception/Error Details</title></head><body>");
if(statusCode != 500){
out.write("<h3>Error Details</h3>");
out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
out.write("<strong>Requested URI</strong>:"+requestUri);
}else{
out.write("<h3>Exception Details</h3>");
out.write("<ul><li>Servlet Name:"+servletName+"</li>");
out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
out.write("<li>Requested URI:"+requestUri+"</li>");
out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
out.write("</ul>");
}
out.write("<br><br>");
out.write("<a href=\"login.html\">Login Page</a>");
out.write("</body></html>");
}
}
****************************************************************************************************************************************************************************
Authenticationfilter.java
package com.ebgt.servlet.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
public class AuthenticationFilter implements Filter {
private Logger logger = Logger.getLogger(AuthenticationFilter.class);
public void init(FilterConfig fConfig) throws ServletException {
logger.info("AuthenticationFilter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
logger.info("Requested Resource::"+uri);
HttpSession session = req.getSession(false);
if(session == null && !(uri.endsWith("html") || uri.endsWith("Login") || uri.endsWith("Register"))){
logger.error("Unauthorized access request");
res.sendRedirect("login.html");
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
public void destroy() {
//close any resources here
}
}
****************************************************************************************************************************************************************************
AppcontextListner.java
package com.ebgt.servlet.listeners;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import com.ebgt.util.DBConnectionManager;
public class AppContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext ctx = servletContextEvent.getServletContext();
//initialize DB Connection
String dbURL = ctx.getInitParameter("dbURL");
String user = ctx.getInitParameter("dbUser");
String pwd = ctx.getInitParameter("dbPassword");
try {
DBConnectionManager connectionManager = new DBConnectionManager(dbURL, user, pwd);
ctx.setAttribute("DBConnection", connectionManager.getConnection());
System.out.println("DB Connection initialized successfully.");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//initialize log4j
String log4jConfig = ctx.getInitParameter("log4j-config");
if(log4jConfig == null){
System.err.println("No log4j-config init param, initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}else {
String webAppPath = ctx.getRealPath("/");
String log4jProp = webAppPath + log4jConfig;
File log4jConfigFile = new File(log4jProp);
if (log4jConfigFile.exists()) {
System.out.println("Initializing log4j with: " + log4jProp);
DOMConfigurator.configure(log4jProp);
} else {
System.err.println(log4jProp + " file not found, initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}
}
System.out.println("log4j configured properly");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
Connection con = (Connection) servletContextEvent.getServletContext().getAttribute("DBConnection");
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}