Create a simple bulletin board with Java + MySQL

board.PNG

I made a simple bulletin board using mysql.

Overview

-Display ID, name, comment, and time stamp on the bulletin board. -If no name or comment is entered, an error message will pop up.

Where I had a hard time

-I didn't know how to retrieve the data stored in the DB. At first I tried to retrieve the ID, name, comment, and timestamp separately in the array, but it didn't work. ArrayList can store an entire instance!

-I didn't know how to retrieve the contents of ArrayList with jsp. I tried to take it out with the EL method, but it didn't work. I was able to retrieve it using forEach in JSTL's core tag library.

-I get a time zone error when connecting to mysql. Change the connection URL referring to the following. If you want to use Japan time, change the end to JST. What to do if you get an error in "The server time zone value" when running-app with Grails 3 + MySQL

Source code

model

Board.java


package model;

import java.io.Serializable;
import java.sql.Timestamp;

public class Board implements Serializable {
	private int id;
	private String name;
	private String comment;
	private Timestamp time;


	public Timestamp getTime() {
		return time;
	}
	public void setTime(Timestamp time) {
		this.time = time;
	}
	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 getComment() {
		return comment;
	}
	public void setComment(String comment) {
		this.comment = comment;
	}

}

FindCommentDAO.java


package model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class FindCommentDAO {

	public List<Board> findcomment() {

		// id,name,List to store comments
		List<Board> list = new ArrayList<>();

		final String jdbcId = "id";
		final String jdbcPass = "password";
		final String jdbcUrl = "jdbc:mysql://localhost:3306/dbname?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=JST";

		Connection con = null;

		try {

			con = DriverManager.getConnection(jdbcUrl, jdbcId, jdbcPass);

			System.out.println("Connected....");

			try {
				Statement st = con.createStatement();
				String sql = "select * from board";

				try {
					//Send sql
					ResultSet rs = st.executeQuery(sql);

					while (rs.next()) {
						//Id retrieved from DB,name,set comment to JavaBeans
						Board bo = new Board();
						bo.setId(rs.getInt("id"));
						bo.setName(rs.getString("name"));
						bo.setComment(rs.getString("comment"));
						bo.setTime(rs.getTimestamp("time"));

						//Store one in the list. Elements are added at the end.
						list.add(bo);
					}

					rs.close();
					st.close();

				} catch (SQLException e) {
					e.printStackTrace();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				//Lost database connection
				if (con != null) {
					try {
						con.close();

					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Connection Failed.");
			return null;
		}
		return list;

	}

}

FindCommentLogic.java


package model;

import java.util.List;

public class FindCommentLogic {
	public List<Board> executeFindComment() {
		FindCommentDAO fcdao = new FindCommentDAO();
		List<Board> list = fcdao.findcomment();
		return list;
	}

}

AddCommentDAO.java


package model;

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

public class AddCommentDAO {

	//ID to DB,name,Method to add comment
	public AddCommentDAO(Board bo) {

		if(bo.getName().isEmpty()) {
			bo.setName( "Anonymous");
		}
		if(bo.getComment().isEmpty()) {
			bo.setComment( "no comment");
		}


		final String jdbcId = "id";
		final String jdbcPass = "password";
		final String jdbcUrl = "jdbc:mysql://localhost:3306/dbname?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=JST";

		Connection con = null;

		try {

			con = DriverManager.getConnection(jdbcUrl, jdbcId, jdbcPass);

			System.out.println("Connected....");

			try {

				PreparedStatement ps = con.prepareStatement("INSERT INTO board (name, comment) VALUES (?, ?)");

				ps.setString(1, bo.getName());
				ps.setString(2, bo.getComment());

				//Send stationery
				int r = ps.executeUpdate();

				if (r != 0) {
					System.out.println(r + "Added writing.");
				} else {
					System.out.println("Could not write.");
				}

				ps.close();

			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				//Lost database connection
				if (con != null) {
					try {
						con.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (SQLException e) {

			e.printStackTrace();
			System.out.println("Connection Failed.");

		}

	}

}

AddCommentLogic


package model;

public class AddCommentLogic {
	public void executeAddComment(Board bo) {
		AddCommentDAO acdao = new AddCommentDAO(bo);
	}
}

view

main.jsp


<%@ 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>
<meta charset="UTF-8">


<script type="text/javascript">

function check(){
	var flag = 0;

	if(document.form1.name.value == ""){
		flag = 1;
	}
	else if(document.form1.comment.value == ""){
		flag = 1;
	}

	if(flag){
		window.alert('Please enter your name and comment'); 
		return false; //Stop sending
	}
	else{
		return true; //Perform send
	}
}
</script>

<title>Bulletin board</title>
</head>
<body>
<form action="/board/BoardServlet" method="post" name="form1" onSubmit="return check()">
<p>name:<input type="text" name="name"></p>
<p>comment:<br>
<textarea name="comment" rows="5" cols="40"></textarea>
</p>
<p><input type="submit" value="Send"><input type="reset" value="reset">
</p>
</form>

<c:forEach var="list" items="${listAttribute}">
<p>ID:<c:out value="${list.id}"/>name:<c:out value="${list.name}"/>date:<c:out value="${list.time}"/><br>
<c:out value="${list.comment}"/></p>
</c:forEach>

</body>
</html>

controller

BoardServlet.java


package servlet;

import java.io.IOException;
import java.util.List;

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 model.AddCommentLogic;
import model.Board;
import model.FindCommentLogic;

/**
 * Servlet implementation class BoardServlet
 */
@WebServlet("/BoardServlet")
public class BoardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public BoardServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//I want to move to the listener class
		request.setCharacterEncoding("UTF-8");

		//Check existing comments
		FindCommentLogic fcl = new FindCommentLogic();
		List<Board> list = fcl.executeFindComment();

		//Save comment list in session scope
		HttpSession session = request.getSession();
		session.setAttribute("listAttribute", list);

		RequestDispatcher rd =request.getRequestDispatcher("/WEB-INF/jsp/main.jsp");
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");

		//Get the entered value
		String name = request.getParameter("name");
		String comment = request.getParameter("comment");

		//Store in JavaBeans
		Board bo = new Board();
		bo.setName(name);
		bo.setComment(comment);

		//Store in mysql
		AddCommentLogic acl = new AddCommentLogic();
		acl.executeAddComment(bo);

		//Get the comment just entered and the existing comment from mysql
		FindCommentLogic fcl = new FindCommentLogic();
		List<Board> list = fcl.executeFindComment();

		//Save comment list in session scope
		HttpSession session = request.getSession();
		session.setAttribute("listAttribute", list);

		RequestDispatcher rd =request.getRequestDispatcher("/WEB-INF/jsp/main.jsp");
		rd.forward(request, response);

	}

}

Recommended Posts

Create a simple bulletin board with Java + MySQL
Try to create a bulletin board in Java
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
Create a simple web application with Dropwizard
Create a simple on-demand batch with Spring Batch
[Rails withdrawal] Create a simple withdrawal function with rails
Create a MySQL environment with Docker from 0-> 1
Create a simple bar chart with MPAndroidChart
Create a simple web server with the Java standard library com.sun.net.httpserver
Create a simple search app with Spring Boot
Create a CSR with extended information in Java
[Windows] [IntelliJ] [Java] [Tomcat] Create a Tomcat9 environment with IntelliJ
Let's create a timed process with Java Timer! !!
[Java] Create a filter
[Java] Create a collection with only one element
Create a docker image that runs a simple Java app
[Beginner] Create a competitive game with basic Java knowledge
[Note] Create a java environment from scratch with docker
Create a simple demo site with Spring Security with Spring Boot 2.1
Create a java method [Memo] [java11]
[Java] Create a temporary file
Create a playground with Xcode 12
Connect to MySQL 8 with Java
[Java] Draw a simple pattern
I tried to create a java8 development environment with Chocolatey
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ③ ~ Add Validation ~
[Beginner] Try to make a simple RPG game with Java ①
Create a SlackBot with AWS lambda & API Gateway in Java
A Simple CRUD Sample Using Java Servlet / JSP and MySQL
Create an immutable class with JAVA
Create a Vue3 environment with Docker!
Build a Java project with Gradle
3 Implement a simple interpreter in Java
Create a Java project using Eclipse
[Java] How to create a folder
A simple sample callback in Java
Create exceptions with a fluid interface
Create a Maven project with a command
Implement a simple Web REST API server with Spring Boot + MySQL
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ④ ~ Customize error messages ~
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
I can't create a Java class with a specific name in IntelliJ
Create a high-performance enum with fields and methods like Java with JavaScript
I tried to make a group function (bulletin board) with Rails
[Java] Create and apply a slide master
Get a backup with mysqldump (Docker's MySQL)
[Java] Create an executable module with Gradle
Create a jar file with the command
[Rails6] Create a new app with Rails [Beginner]
Beginners create web applications with Java and MySQL (adding at any time)
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ② ~ Screen and function creation ~
Create Rails 6 + MySQL environment with Docker compose
Create a GUI JSON Viewer with Ruby/GTK3
[Java] Create a jar file with both compressed and uncompressed with the jar command
Let's create a Java development environment (updating)
I want to create a dark web SNS with Jakarta EE 8 with Java 11
Create a TODO app in Java 7 Create Header
Create a temporary class with new Object () {}
[docker] [nginx] Make a simple ALB with nginx
[Rails] Let's create a super simple Rails API
Build a bulletin board API with authentication and authorization with Rails 6 # 1 Environment construction