================================================================================
 employee-form  -  JSP Form + Servlet + JDBC + MySQL, and Session Management
================================================================================

Lab project for "Topic 3 - JSP and SERVLET, Session 1: Forms and Session
Management" (ICT Academy / Vidya Sagar Institute).

It demonstrates the full form round-trip taught in the PPT:

    JSP form  ->  Servlet (doPost)  ->  JavaBean  ->  DAO (JDBC)  ->  MySQL

and then the HttpSession API (isNew, getId, getAttribute, setAttribute,
invalidate, setMaxInactiveInterval).

Source of the samples:  D:\sandeep\jsp-topic3\
                       "Session 1 - Forms and Session management"\
                       forms_and_session_management.jsp


--------------------------------------------------------------------------------
1. APPLICATION URL
--------------------------------------------------------------------------------

    http://localhost:9090/employee-form/employeeregister.jsp

    (Requires the Tomcat server to be running - see section 5.)

    Shortcut index page listing every link:

    http://localhost:9090/employee-form/


--------------------------------------------------------------------------------
2. TECHNOLOGIES USED
--------------------------------------------------------------------------------

    Project type     Dynamic Web Project (WTP)
    Java             JDK 1.8 (source / target 1.8)
    Web standard     Jakarta EE / Java EE Web 4.0 (jst.web facet 4.0)
    Server runtime   Apache Tomcat 9.0.x
    Servlet API      javax.servlet (servlet-api.jar shipped with Tomcat 9)
    IDE              Eclipse IDE for Enterprise Java and Web Developers
    Database         MySQL 8 (schema "employees", table "employee")
    Driver           mysql-connector-java-8.0.13.jar
    JSTL             jstl-1.2.jar + standard-1.1.2.jar (used only by
                     rewriteurl.jsp)
    Build tool       None (Eclipse only - no Maven / Gradle in this project)


--------------------------------------------------------------------------------
3. PREREQUISITES
--------------------------------------------------------------------------------

    a) JDK 8 installed. Register it under
       Window > Preferences > Java > Installed JREs > Add... and set it as the
       Workspace default.

    b) Eclipse IDE for Enterprise Java and Web Developers (the package that
       ships "Eclipse Web Developer Tools"). The JST facets and the Servers
       view come from that package.

    c) Apache Tomcat 9.0.x extracted somewhere. This machine uses:
       D:\sandeep\javaBasics-workspace\apache-tomcat-9.0.122

    d) MySQL 8 running, with the "employees" database created (section 4).

    e) This project folder imported as an existing project (section 5, STEP 1).
       Do NOT create a new project - the .project / .classpath / .settings
       files already carry the correct configuration.


--------------------------------------------------------------------------------
4. DATABASE SETUP
--------------------------------------------------------------------------------

Open a MySQL client (MySQL Workbench, or the mysql.exe command line) and run:

    CREATE DATABASE IF NOT EXISTS employees;
    USE employees;

    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;

Then confirm the insert landed:

    SELECT * FROM employees.employee;

IMPORTANT - the credentials in EmployeeDao must match your MySQL.

    File: src/main/java/net/javaguides/employeemanagement/dao/EmployeeDao.java

        private static final String URL =
            "jdbc:mysql://localhost:3306/employees"
            + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";

        private static final String USER     = "root";
        private static final String PASSWORD = "system";      <-- change this

The two extra URL parameters are required, not optional:

    serverTimezone=UTC           without it the connector throws
                                 "The server time zone value ... is
                                  unrecognized"
    allowPublicKeyRetrieval=true MySQL 8 defaults to caching_sha2_password;
                                 without this the connector throws
                                 "Public Key Retrieval is not allowed"


--------------------------------------------------------------------------------
5. PROJECT STRUCTURE
--------------------------------------------------------------------------------

    employee-form/
     |
     +-- readme.txt                     This file
     +-- .classpath                     JRE + servlet-api.jar + web containers
     +-- .project                       Eclipse project descriptor
     +-- build/classes/                 Compiled .class output folder
     |
     +-- .settings/                     Facets, JDT compiler, JSDT settings
     |
     +-- src/main/java/net/javaguides/employeemanagement/
     |       bean/Employee.java        JavaBean: firstName, lastName, username,
     |                                 password, address, contact
     |       dao/EmployeeDao.java      JDBC INSERT via PreparedStatement
     |       web/EmployeeServlet.java  @WebServlet("/register") - doPost
     |       web/SessionDemoServlet.java @WebServlet("/sessionDemo")
     |       web/LogoutServlet.java    @WebServlet("/logout") - invalidate()
     |
     +-- src/main/webapp/
             index.jsp                  Index of all the links (START HERE)
             employeeregister.jsp       Registration form + dummy data button
             employeedetails.jsp        Success page (after the redirect)
             rewriteurl.jsp             c:url URL rewriting + hidden field
             WEB-INF/web.xml            Minimal 4.0 descriptor. All servlets
                                       are declared with @WebServlet, so no
                                       <servlet> entries are needed.
             WEB-INF/lib/
                 mysql-connector-java-8.0.13.jar
                 jstl-1.2.jar
                 standard-1.1.2.jar
             META-INF/MANIFEST.MF

    Context path when deployed by Eclipse: /employee-form
    (it comes from the project name, so keep the project named
     "employee-form")


--------------------------------------------------------------------------------
6. SETUP AND RUNNING IN ECLIPSE  (step by step)
--------------------------------------------------------------------------------

STEP 1 - Import the project
    1. Start Eclipse.
    2. File > Import... > General > Existing Projects into Workspace > Next.
    3. Select root directory:
           D:\sandeep\javaBasics-workspace\employee-form
    4. Tick "employee-form" in the Projects list > Finish.

    If Eclipse marks the project red, work through STEP 2 and STEP 3 - those
    are environment path issues, not a broken project.


STEP 2 - Confirm the JRE is Java 8
    1. Right-click "employee-form" > Properties > Java Build Path > Libraries.
    2. Select the JRE System Library. It should read "JavaSE-1.8".
       If it shows JavaSE-20 or has a red cross, click "Edit..." and point it
       at your JDK 1.8, or at the Workspace default JRE.

    Why this matters: the project was originally generated with the Java 20
    facet while Tomcat runs on JDK 8. Class files compiled above major
    version 52 are silently not loaded by the container, and every servlet
    URL returns 404 with NO error in the log. The facet and the compiler
    settings are already corrected in this project.


STEP 3 - Fix the servlet-api.jar path  (IMPORTANT on a new machine)
    .classpath stores an ABSOLUTE path to Tomcat's jar:

        <classpathentry kind="lib"
            path="D:/sandeep/javaBasics-workspace/apache-tomcat-9.0.122/lib/servlet-api.jar"/>

    If Tomcat lives elsewhere the entry shows as missing and the servlets
    will not compile.

    Fix it either way:

    Option A (recommended) - let Eclipse manage it:
        Project > Properties > Java Build Path > Libraries
        > select the broken servlet-api.jar > Remove
        > Add Library... > "Server Runtime" > Next
        > pick "Apache Tomcat v9.0" > Finish > Apply and Close.

    Option B - browse to your own copy:
        Add JARs... > <your-tomcat>\lib\servlet-api.jar > Apply and Close.


STEP 4 - Verify the facets
    Right-click "employee-form" > Properties > Facets. You should see:

        Dynamic Web Module          4.0
        Java                        1.8
        JavaScript / wst.jsdt.web   1.0


STEP 5 - Configure the Tomcat server
    1. Window > Show View > Servers.
    2. Create a server if none is listed:
       "Apache Tomcat" > "Tomcat v9.0 Server" > Next.
    3. Tomcat installation directory -> your Tomcat 9 folder (the one holding
       bin\ and conf\) > Next > Finish.
    4. Open "Server Locations". The Application name / path must read:

           /employee-form

       This is what makes
       http://localhost:9090/employee-form/... resolve.
    5. Open the "Ports" tab and set HTTP to 9090. Port 9090 is what every URL
       in this file assumes.


STEP 6 - Add the project to the server
    Servers view > right-click the Tomcat server > "Add and Remove Projects..."
    > select "employee-form" > Add > Finish.


STEP 7 - Run
    1. Right-click the Tomcat server > "Start". Wait for "Server startup in".
    2. Right-click the "employee-form" project > "Run As" > "Run on Server".
    3. Open:

           http://localhost:9090/employee-form/employeeregister.jsp


--------------------------------------------------------------------------------
7. HOW TO USE THE APPLICATION
--------------------------------------------------------------------------------

    1. Open    http://localhost:9090/employee-form/employeeregister.jsp
    2. Press "Load Dummy Data" to fill all six fields with sample values, or
       type your own.
    3. Press "Submit". The browser POSTs to /employee-form/register.
    4. EmployeeServlet reads the six parameters, maps them onto the Employee
       bean, and calls EmployeeDao.registerEmployee(...).
    5. On success the servlet redirects to employeedetails.jsp, which shows
       "User successfully registered!".
    6. Check the row landed:

           SELECT * FROM employees.employee;

    7. Submit the form a SECOND time. The corrected DAO omits `id` from the
       INSERT so MySQL assigns 1, then 2, then 3... This is the check that
       proves the fix - see section 9.

    Then the session part:

    8. Open http://localhost:9090/employee-form/sessionDemo.
       The page reports isNew(), getId(), getAttribute(), the creation time
       and the last-accessed time.
    9. Refresh it. isNew() is now false and getId() is unchanged - the
       container sent the JSESSIONID cookie back.
    10. Click "logout (invalidate)". You land back on the demo with a brand new
        session id, because invalidate() expired the old one.
    11. Open rewriteurl.jsp to see c:url and response.encodeURL() appending
        ;jsessionid=... (visible only when the browser is not keeping cookies).


--------------------------------------------------------------------------------
8. ALL AVAILABLE URLS  (server running on port 9090)
--------------------------------------------------------------------------------

    Index / start here      http://localhost:9090/employee-form/
    Registration form       http://localhost:9090/employee-form/employeeregister.jsp
    Success page            http://localhost:9090/employee-form/employeedetails.jsp
    Session demo            http://localhost:9090/employee-form/sessionDemo
    Logout / invalidate     http://localhost:9090/employee-form/logout
    URL rewriting sample    http://localhost:9090/employee-form/rewriteurl.jsp

    (Servlet URLs such as /register are POST targets and have no page of
     their own; hitting them in a browser returns HTTP 405.)


--------------------------------------------------------------------------------
9. DEVIATIONS FROM THE PPT  (and why)
--------------------------------------------------------------------------------

The PPT code is reproduced faithfully in the teaching file, but this runnable
project corrects four things that would otherwise fail.

    (a) Hard-coded primary key
        The PPT binds  id = 1  explicitly:
            preparedStatement.setInt(1, 1);
        with `id` also listed in the INSERT column list. The FIRST submit
        works; every submit after it fails with
            Duplicate entry '1' for key 'PRIMARY'
        Fix: drop `id` from the INSERT and let AUTO_INCREMENT assign it.

    (b) Deprecated driver class
        The PPT calls Class.forName("com.mysql.jdbc.Driver"). Connector 8.x
        prints a deprecation warning for that name.
        Fix: use com.mysql.cj.jdbc.Driver.

    (c) Incomplete JDBC URL
        The PPT uses only ?useSSL=false. Against MySQL 8 with connector 8.0.13
        that throws "Public Key Retrieval is not allowed".
        Fix: add serverTimezone=UTC and allowPublicKeyRetrieval=true.

    (d) Servlet methods left empty
        The PPT's Session 3 skeleton has empty method bodies. Here every
        servlet method is fully implemented.

One deliberate non-change: the explicit Class.forName(DRIVER) call is KEPT,
even though JDBC 4.0+ normally auto-registers drivers. DriverManager holds a
single static driver list per JVM, initialised from whichever classloader
loaded it first - inside Tomcat that is often not this webapp's loader, and
the symptom is "No suitable driver found" even though the jar is sitting in
WEB-INF/lib. The explicit load makes registration deterministic.


--------------------------------------------------------------------------------
10. COMMON PROBLEMS AND FIXES
--------------------------------------------------------------------------------

    "No suitable driver found for jdbc:mysql://..."
        -> The driver class was never registered, OR the jar is missing.
           This project loads the driver explicitly, so if it still happens,
           confirm WEB-INF/lib/mysql-connector-java-8.0.13.jar exists, then
           do a full republish: right-click project > Refresh, restart the
           server in the Servers view.

    "Access denied for user 'root'@'localhost'"
        -> The MySQL password in EmployeeDao does not match your server.
           Edit USER / PASSWORD in EmployeeDao (section 4). This is the most
           common first-run failure and it is NOT a code bug.

    "Public Key Retrieval is not allowed"
        -> allowPublicKeyRetrieval=true is missing from the URL (section 4).

    "The server time zone value ... is unrecognized"
        -> serverTimezone is missing from the URL (section 4).

    "Unknown database 'employees'"
        -> The CREATE DATABASE in section 4 was never run.

    HTTP 404 on EVERY servlet URL, and nothing in the console
        -> The classes were compiled for a newer JDK than the one Tomcat runs.
           This is the silent failure described in STEP 2. Set the facet and
           the compiler level to 1.8, then Project > Clean.

    HTTP 404 only on /employeeregister.jsp
        -> The JSP was not published. Right-click project > Refresh, then
           restart the server.

    HTTP 405 on /register
        -> Expected. It only answers POST. Use the form.

    "The type javax.servlet.http.HttpServlet cannot be resolved"
        -> The servlet-api.jar classpath entry is broken. Repeat STEP 3.

    Port 9090 already in use
        -> Another Tomcat owns it. Do not start a second Tomcat by hand with
           catalina.bat while Eclipse is managing the server - they fight over
           the port. Stop the extra one, or change the port in the server's
           Ports tab.

    Changes to a JSP do not show up
        -> Cached page. Ctrl+F5, then restart the server if needed.

    Tomcat will not start: "Port 8105 already in use"
        -> That is the SHUTDOWN port configured in conf/server.xml. A stray
           catalina.bat instance is holding it; stop it from Task Manager or
           with:  netstat -ano | findstr 8105   then kill that PID.


--------------------------------------------------------------------------------
11. STOPPING THE SERVER
--------------------------------------------------------------------------------

    Servers view > right-click the Tomcat server > "Stop".

    Do not also leave a manually started catalina.bat running - it will hold
    ports the Eclipse server needs and cause "port already in use" errors.


================================================================================
 End of file
================================================================================