[Java / Eclipse / Servlet / JSP / PostgreSQL] A WEB application framework with data posting / saving / editing / updating / deleting functions

Content of this article

Developed an application with data posting / saving / editing / updating / deleting functions in Java, and a memorandum

Characteristics of the person who wrote this article

・ I have experience of uploading a WEB application that has data posting / saving / editing / updating / deleting functions to the production environment with Rails. ・ No experience in developing web applications in Java

Development environment

item
PC MacBook Air
OS MacOS Mojave
language Java
IDE Eclipse
DB PostgreSQL
DB management pgAdmin
version control GitHub
browser Chrome

Prerequisites

DB (1) The functions to be implemented and the corresponding Servlet / JSP are as follows.

process method Servlet JSP
/list GET ListServlet.java list.jsp
/show GET ShowServlet.java list.jsp
/new GET NewServlet.java new.jsp
/create POST CreateServlet.java -
/edit GET EditServlet.java edit.jsp
/update POST UpdateServlet.java -
/delete POST DeleteServlet.java -

② Prepare a POSTS table on the MEMO database and connect the table to the application.

item value
DB address http://localhost:5432/
DB memo
username SAMPLEUSER
password SAMPLEPASSWORD

SQL


CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title varchar,
content varchar
);

SQL


SELECT * FROM posts;

SQL execution result


id |     title     |             content              
----+---------------+----------------------------------
 14 | 2019/05/15    | memo app by Java Servlet and JSP
 15 | sample title  | sample content
 16 | memoapp       | made of Java Servlet and JSP
 17 | sample_edited | sample_edited
 21 | sample_edited | sample_edited
 22 | sample        | sample
(6 rows)

Eclipse ① WEB application is created by "Dynamic WEB Project"

Other

① Do not consider the commonality of duplicate code this time (2) Front-end design with CSS / JavaScript is not considered this time.

Code example

Servlet ListServlet.java

ListServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/list")
public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
		//DB connection
		String url = "jdbc:postgresql://localhost:5432/memo";
		String user = "SAMPLEUSER";
		String password = "SAMPLEPASSWORD";
		
	    try{
            Class.forName("org.postgresql.Driver");
        } catch(Exception e) {
            e.printStackTrace();
        }
		
		try { 
			Connection connection = DriverManager.getConnection(url, user, password);
			connection.setAutoCommit(false);
			String sql = "SELECT * FROM posts;";
			PreparedStatement statement = connection.prepareStatement(sql);

			
			ResultSet results = statement.executeQuery();
			
			ArrayList<HashMap<String,String>> rows = new ArrayList<HashMap<String,String>>();
			
			while(results.next()) {
				HashMap<String,String> columns = new HashMap<String,String>();
				
				String id = results.getString("id");
				columns.put("id",id);
				
				String title = results.getString("title");
				columns.put("title", title);
				
				String content = results.getString("content");
				columns.put("content",content);
				
				rows.add(columns);
			}
			request.setAttribute("rows", rows);
			results.close();
			statement.close();
		
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/views/list.jsp");
		dispatcher.forward(request,response);
		System.out.println("-----Displayed screen-----");
		System.out.println("/list");
		System.out.println("");
	}

}

ShowServlet.java

ShowServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/show")
public class ShowServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
		//DB connection
		String url = "jdbc:postgresql://localhost:5432/memo";
		String user = "SAMPLEUSER";
		String password = "SAMPLEPASSWORD";
		
	    try{
            Class.forName("org.postgresql.Driver");
        } catch(Exception e) {
            e.printStackTrace();
        }
		
		try { 
			Connection connection = DriverManager.getConnection(url, user, password);
			connection.setAutoCommit(false);
			String sql = "SELECT * FROM posts WHERE id = ?;";
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setInt(1, Integer.parseInt(request.getParameter("id")));
			
			ResultSet results = statement.executeQuery();
			
			ArrayList<HashMap<String,String>> rows = new ArrayList<HashMap<String,String>>();
			
			while(results.next()) {
				
				String id = results.getString("id");
				request.setAttribute("id", id);
				
				String title = results.getString("title");
				request.setAttribute("title", title);

				
				String content = results.getString("content");
				request.setAttribute("content", content);
				

			}
			request.setAttribute("rows", rows);
			System.out.println("-----Stored data-----");
			System.out.println(rows);
			System.out.println("");
			results.close();
			statement.close();
		
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/views/show.jsp");
		dispatcher.forward(request,response);
		System.out.println("-----Displayed screen-----");
		System.out.println("/show?id=" + request.getParameter("id"));
		System.out.println("");
	}

}

NewServlet.java

NewServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/new")
public class NewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/views/new.jsp");
		dispatcher.forward(request,response);
		System.out.println("-----Displayed screen-----");
		System.out.println("/new");
		System.out.println("");
	}

}

CreateServlet.java

CreateServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/create")
public class CreateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
				String title = request.getParameter("title");
				String content = request.getParameter("content");
		
		//DB connection
				String url = "jdbc:postgresql://localhost:5432/memo";
				String user = "SAMPLEUSER";
				String password = "SAMPLEPASSWORD";
				
			    try{
		            Class.forName("org.postgresql.Driver");
		        } catch(Exception e) {
		            e.printStackTrace();
		        }
				
				try { 
					Connection connection = DriverManager.getConnection(url, user, password);
					connection.setAutoCommit(false);
					String sql = "INSERT INTO posts (title,content) VALUES (?,?)" ;
					PreparedStatement statement = connection.prepareStatement(sql);
					statement.setString(1, title);
					statement.setString(2, content);
					int number = statement.executeUpdate();			
					connection.commit();
				} catch(Exception e) {
					e.printStackTrace();
				}
		
		
		
		String forward = "/memo/list";
		response.sendRedirect(forward);
		System.out.println("-----I posted a memo.-----");
		System.out.println("ID: " + request.getParameter("title") + " TITLE: " + request.getParameter("content"));
		System.out.println("");
	}
}


EditServlet.java

EditServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/edit")
public class EditServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
		//DB connection
		String url = "jdbc:postgresql://localhost:5432/memo";
		String user = "SAMPLEUSER";
		String password = "SAMPLEPASSWORD";
		
	    try{
            Class.forName("org.postgresql.Driver");
        } catch(Exception e) {
            e.printStackTrace();
        }
		
		try { 
			Connection connection = DriverManager.getConnection(url, user, password);
			connection.setAutoCommit(false);
			String sql = "SELECT * FROM posts WHERE id = ?;";
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setInt(1, Integer.parseInt(request.getParameter("id")));
			
			ResultSet results = statement.executeQuery();
			
			ArrayList<HashMap<String,String>> rows = new ArrayList<HashMap<String,String>>();
			
			while(results.next()) {
				
				String id = results.getString("id");
				request.setAttribute("id", id);
				
				String title = results.getString("title");
				request.setAttribute("title", title);

				
				String content = results.getString("content");
				request.setAttribute("content", content);
				

			}
			request.setAttribute("rows", rows);
			System.out.println(rows);
			System.out.println("");
			results.close();
			statement.close();
		
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/views/edit.jsp");
		dispatcher.forward(request,response);
		System.out.println("-----Displayed screen-----");
		System.out.println("/edit?id=" + request.getParameter("id"));
		System.out.println("");
	}

}

UpdateServlet.java

UpdateServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
				String title = request.getParameter("title");
				String content = request.getParameter("content");
				int id = Integer.parseInt(request.getParameter("id"));
		
		//DB connection
				String url = "jdbc:postgresql://localhost:5432/memo";
				String user = "SAMPLEUSER";
				String password = "SAMPLEPASSWORD";
				
			    try{
		            Class.forName("org.postgresql.Driver");
		        } catch(Exception e) {
		            e.printStackTrace();
		        }
				
				try { 
					Connection connection = DriverManager.getConnection(url, user, password);
					connection.setAutoCommit(false);
					String sql = "UPDATE posts SET title = ?, content = ? WHERE id = ?";
					PreparedStatement statement = connection.prepareStatement(sql);
					statement.setString(1, title);
					statement.setString(2, content);
					statement.setInt(3, id);
					int number = statement.executeUpdate();			
					connection.commit();
				} catch(Exception e) {
					e.printStackTrace();
				}
		
		
		
		String forward = "/memo/show?id=" + id;
		response.sendRedirect(forward);
		System.out.println("-----The memo has been updated.-----");
		System.out.println("ID: " + request.getParameter("id") + " TITLE: " + request.getParameter("title")  + " CONTENT: " + request.getParameter("content"));
		System.out.println("");
	}
}


DeleteServlet.java

DeleteServlet.java


package sample;

import java.io.IOException;
import javax.servlet.*;
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.*;
import java.sql.*;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
				int id = Integer.parseInt(request.getParameter("id"));
		
		//DB connection
				String url = "jdbc:postgresql://localhost:5432/memo";
				String user = "SAMPLEUSER";
				String password = "SAMPLEPASSWORD";
				
			    try{
		            Class.forName("org.postgresql.Driver");
		        } catch(Exception e) {
		            e.printStackTrace();
		        }
				
				try { 
					Connection connection = DriverManager.getConnection(url, user, password);
					String sql = "DELETE FROM posts WHERE id = ?";
					PreparedStatement statement = connection.prepareStatement(sql);
					statement.setInt(1, id);
					int number = statement.executeUpdate();			
				} catch(Exception e) {
					e.printStackTrace();
				}
		
		
		
		String forward = "/memo/list";
		response.sendRedirect(forward);
		System.out.println("-----I deleted the memo.-----");
		System.out.println("ID: " + request.getParameter("id"));
		System.out.println("");
	}
}


JSP list.jsp

list.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.util.*" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
 <h2>MEMO LIST</h2>
 <p>This app is made by Java Servlet and JSP.</p>



<table>
<tr><th>ID</th><th>TITLE</th></tr>
<% ArrayList<HashMap<String,String>> rows = (ArrayList<HashMap<String,String>>)request.getAttribute("rows"); %>

<% for(HashMap<String,String> columns: rows){ %>
<tr><td><%= columns.get("id") %></td><td><a href="show?id=<%= columns.get("id") %>"><%= columns.get("title") %></a></td></tr>
<% } %>
</table>
 
 <p></p>
 <a href="new">Create new memo</a>
</body>
</html>

show.jsp

show.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.util.*" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
 <h2>MEMO DETAIL</h2>
 <p>This app is made by Java Servlet and JSP.</p>


<br>
<form action="delete?id=<%= request.getAttribute("id") %>" method="POST">
<p>ID: <%= request.getAttribute("id") %></p>
<p>TITLE: <%= request.getAttribute("title") %></p>
<p>CONTENT:</p>
<p><%= request.getAttribute("content") %></p>
<br>
 <a href="edit?id=<%= request.getAttribute("id") %>">Edit</a><br>
 <button>Delete</button><br>
 </form>
<br>
 <a href="list">Return list</a>
</body>
</html>

new.jsp

new.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.util.*" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
 <h2>CREATE NEW MEMO</h2>
 <p>This app is made by Java Servlet and JSP.</p>
<p></p>

<form action="create" method="POST">
<p>TITLE:</p>
<input type=text name="title">
<p>CONTENT:</p>
<input type=text name="content">
<p></p>
 <button>Create</button><br>
 </form>
 
<p></p>
 <a href="list">Cancel</a>
</body>
</html>

edit.jsp

edit.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.util.*" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
 <h2>EDIT MEMO</h2>
 <p>This app is made by Java Servlet and JSP.</p>
<p></p>

<form action="update" method="POST">
<p>ID: <%= request.getAttribute("id") %></p>
<input type='hidden' name='id' value='<%= request.getAttribute("id") %>'>
<p>TITLE:</p>
<input type="text" name="title" value="<%= request.getAttribute("title") %>">
<p>CONTENT:</p>
<input type="text" name="content" value="<%= request.getAttribute("content") %>">
<p></p>
 <button>Update</button><br>
 </form>
 
<p></p>
 <a href="list">Cancel</a>
</body>
</html>

What I want to do in the future

(1) Implementation of login / log-off function ② Password encryption ③ Addition of validation (constraint) ④ Part template ⑤ Improve design ability through WEB application development (household account book application attached by double-entry bookkeeping) in Java

Recommended Posts

[Java / Eclipse / Servlet / JSP / PostgreSQL] A WEB application framework with data posting / saving / editing / updating / deleting functions
Until you create a Web application with Servlet / JSP (Part 1)
Try developing a containerized Java web application with Eclipse + Codewind
Comparison of WEB application development with Rails and Java Servlet + JSP
[Java] Deploy a web application created with Eclipse + Maven + Ontology on Heroku
Basic Web application creation Servlet / JSP (posting screen)
Web application development memo with MVN, Tomcat, JSP / Servlet with VScode
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
[Probably the easiest] WEB application development with Apache Tomcat + Java Servlet
Build a web application with Javalin
Creating a java web application development environment with docker for mac part1
Create a java web application development environment with docker for mac part2