Een Login application with servlet and jsp

In this web application we will servlets and jsp's as technology

   register
     + src
     | + main
     |   + java 
     |   | + com
     |   |   + littleworld
     |   |     + register
     |   |       + model
     |   |          - Login.java
     |   |       + servlets
     |   |          - LoginCreateServlet.java
     |   |          - LoginListServlet.java
     |   |          - LoginDeleteServlet.java
     |   |       + services
     |   |          - LoginMockService.java
     |   |          - LoginJDBCService.java
     |   + webapp
     |     - loginForm.jsp
     |     - loginList.jsp
     - pom.xml
     - create.sql

Maven POM

In the POM we define the library dependencies of this project

The dependencies are:

We will use the jetty plugin


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.littleworld</groupId>
  <artifactId>register</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>register</name>

  <properties>
    <jdk.version>1.8</jdk.version>
    <jstl.version>1.2</jstl.version>
    <servlet.version>3.1.0</servlet.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.37</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.3.6.v20151106</version>
        <configuration>
          <scanIntervalSeconds>10</scanIntervalSeconds>
          <webApp>
            <contextPath>/register</contextPath>
          </webApp>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <wtpversion>2.0</wtpversion>
          <wtpContextName>register</wtpContextName>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Model

This project uses the login as model

The fields in the model will be used in the views form and list. Apart from the id field.


package com.littleworld.register.model;

public class Login {
  int id;
  String email;
  String password;

  public Login(int id, String email, String password) {
    this.id = id;
    this.email = email;
    this.password = password;
  }

  public int getId() {
    return id;
  }
  public void setId(int id)  {
    this.id = id;
  } 
  public String getEmail() {
    return email;
  }
  public void setEmail(String email)  {
    this.email = email;
  } 
  public String getPassword() {
    return password;
  }
  public void setPassword(String password)  {
    this.password = password;
  } 
}

The HTML View

HTML List

The list page act as the landing page

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
  <title>login list</title>
</head>
<body>

  <jsp:include page="loginForm.jsp" />
  <hr>
  <table>
    <tr><th>email</th><th>password</th></tr>
 
    <c:forEach items="${logins}" var="login">
    <tr><td>${login.email}</td><td>${login.password}</td><td><a href="delete?id=${login.id}">delete</a></tr>
    </c:forEach>  

  </table>
</body>
</html>

The HTML form

<form action="create" method="post">
    <table>
      <tr><td>email:</td><td><input type='text' name='email'></td></tr>
      <tr><td>password:</td><td><input type='text' name='password'></td></tr>
      <tr><td><input type="submit" name="naam" value="OK"></td><td></td></tr>
    </table>
  </form>

Servlets

We will use 3 servlets
package com.littleworld.register.servlets;

import java.io.IOException;
import java.util.UUID;
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 com.littleworld.register.model.*;
import com.littleworld.register.services.*;


@WebServlet("/create")
public class LoginCreateServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");

    
    Login login = new Login(0, email, password);

    LoginMockService.getInstance().create(login);
    //LoginJDBCService.getInstance().create(login);
    response.sendRedirect("list");
  }
}

package com.littleworld.register.servlets;

import java.io.IOException;
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 java.util.List;

import com.littleworld.register.model.*;
import com.littleworld.register.services.*;

@WebServlet("/list")
public class LoginListServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
  
    List<Login> logins = LoginMockService.getInstance().findAll();
    //List<Login> logins = LoginJDBCService.getInstance().findAll();
    request.setAttribute("logins", logins);
    request.getServletContext().getRequestDispatcher("/loginList.jsp").forward(request, response);
  }
}

package com.littleworld.register.servlets;

import java.io.IOException;
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 com.littleworld.register.model.*;
import com.littleworld.register.services.*;


@WebServlet("/delete")
public class LoginDeleteServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
   
   
    int id = request.getParameter("id") != null ? Integer.parseInt(request.getParameter("id")) : 0;

    LoginMockService.getInstance().delete(id);
    //LoginJDBCService.getInstance().delete(id);
    response.sendRedirect("list");
  }
}

Services

The service layer

LoginService contains 3 methodes supporting the 3 servlets We support two different implementations - LoginService will keep the logins in an ArrayList - In the LoginJDBCService the logins are presisted in a mysql database

package com.littleworld.register.services;

import java.util.List;
import java.util.ArrayList;
import com.littleworld.register.model.*;

public class LoginMockService {

    // create singleton
    private static LoginMockService instance = new LoginMockService();

    public static LoginMockService getInstance() {
      return instance;
    }

    private LoginMockService() {}
    
    // generate id with auto increment    
    int uniqueId = 1;

    List<Login> logins = new ArrayList<Login>();

    public Login create(Login login ) {
        login.setId(uniqueId++);
        logins.add(login);
        return login;
    }

    public List<Login> findAll() {
        return logins;
    }
 
    public Login findById(int id) {
        return logins.get(id);
    }

    public void delete(int id) {
      for (int i = 0; i <  logins.size(); i++) {
        if (logins.get(i).getId() == id) { 
          logins.remove(i);
          break;
        }
      }
    }
}


package com.littleworld.register.services;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.*;

import com.littleworld.register.model.*;

public class LoginJDBCService {

    // create singleton
    private static LoginJDBCService instance = new LoginJDBCService();

    public static LoginJDBCService getInstance() {
      return instance;
    }

    private LoginJDBCService() {}
  
    Connection getConnection() {
      Connection connection = null;
      try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root", "");
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      return connection;
    }

    public Login create(Login login ) {
      String sql = "INSERT INTO LOGIN " + "(id, email, password) VALUES (NULL, ?, ?)";
      try {
        Connection connection = getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, login.getEmail());ps.setString(2, login.getPassword());
        ps.executeUpdate();
        ps.close();
      } catch (SQLException e) { 
        e.printStackTrace();
      }
      return login;
    }

    public List<Login> findAll() {
      String sql = "SELECT * FROM LOGIN";
      List<Login> logins = new ArrayList<Login>();
      try {
        Connection connection = getConnection();
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
           logins.add(new Login(rs.getInt("id"), rs.getString("email"), rs.getString("password") ));
        }
      } catch (SQLException e) { 
        e.printStackTrace();
      }
      return logins;
    }
 
    public Login findById(int id) {
        return null;
    }

    public void delete(int id) {
      String sql = "DELETE FROM LOGIN WHERE ID = ?";
      try {
        Connection connection = getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setInt(1, id);
        ps.executeUpdate();
        ps.close();
      } catch (SQLException e) { 
        e.printStackTrace();
      }
    }
}

the create table script

create table login (
  id integer primary key auto_increment,
  email varchar(255),
  password varchar(255)
);

Run the application

To run the application. Goto the root directory of the application and type

(Maven should in the enviroment variable PATH; and JAVA_HOME should be set to the jdk installation dir)

mvn jetty:run
http://localhost:8080/register/list