Een Student application with servlet and jsp

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

   students
     + src
     | + main
     |   + java 
     |   | + com
     |   |   + littleworld
     |   |     + students
     |   |       + model
     |   |          - Student.java
     |   |       + servlets
     |   |          - StudentCreateServlet.java
     |   |          - StudentListServlet.java
     |   |          - StudentDeleteServlet.java
     |   |       + services
     |   |          - StudentMockService.java
     |   |          - StudentJDBCService.java
     |   + webapp
     |     - studentForm.jsp
     |     - studentList.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>students</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>students</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>/students</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>students</wtpContextName>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Model

This project uses the student as model

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


package com.littleworld.students.model;

public class Student {
  int id;
  String name;
  String address;
  String city;

  public Student(int id, String name, String address, String city) {
    this.id = id;
    this.name = name;
    this.address = address;
    this.city = city;
  }

  public int getId() {
    return id;
  }
  public void setId(int id)  {
    this.id = id;
  } 
  public String getName() {
    return name;
  }
  public void setName(String name)  {
    this.name = name;
  } 
  public String getAddress() {
    return address;
  }
  public void setAddress(String address)  {
    this.address = address;
  } 
  public String getCity() {
    return city;
  }
  public void setCity(String city)  {
    this.city = city;
  } 
}

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>student list</title>
</head>
<body>

  <jsp:include page="studentForm.jsp" />
  <hr>
  <table>
    <tr><th>name</th><th>address</th><th>city</th></tr>
 
    <c:forEach items="${students}" var="student">
    <tr><td>${student.name}</td><td>${student.address}</td><td>${student.city}</td><td><a href="delete?id=${student.id}">delete</a></tr>
    </c:forEach>  

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

The HTML form

<form action="create" method="post">
    <table>
      <tr><td>name:</td><td><input type='text' name='name'></td></tr>
      <tr><td>address:</td><td><input type='text' name='address'></td></tr>
      <tr><td>city:</td><td><input type='text' name='city'></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.students.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.students.model.*;
import com.littleworld.students.services.*;


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

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

    
    Student student = new Student(0, name, address, city);

    StudentMockService.getInstance().create(student);
    //StudentJDBCService.getInstance().create(student);
    response.sendRedirect("list");
  }
}

package com.littleworld.students.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.students.model.*;
import com.littleworld.students.services.*;

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

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
  
    List<Student> students = StudentJDBCService.getInstance().findAll();
    request.setAttribute("students", students);
    request.getServletContext().getRequestDispatcher("/studentList.jsp").forward(request, response);
  }
}

package com.littleworld.students.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.students.model.*;
import com.littleworld.students.services.*;


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

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

    StudentJDBCService.getInstance().delete(id);
    response.sendRedirect("list");
  }
}

Services

The service layer

StudentService contains 3 methodes supporting the 3 servlets In the StudentJDBCService the students are presisted in a mysql database

package com.littleworld.students.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.students.model.*;

public class StudentJDBCService {

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

    public static StudentJDBCService getInstance() {
      return instance;
    }

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

    public Student create(Student student ) {
      String sql = "INSERT INTO STUDENT " + "(id, name, address, city) VALUES (NULL, ?, ?, ?)";
      try {
        Connection connection = getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, student.getName());ps.setString(2, student.getAddress());ps.setString(3, student.getCity());
        ps.executeUpdate();
        ps.close();
      } catch (SQLException e) { 
        e.printStackTrace();
      }
      return student;
    }

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

    public void delete(int id) {
      String sql = "DELETE FROM STUDENT 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 student (
  id integer primary key auto_increment,
  name varchar(255),
  address varchar(255),
  city 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/students/list