Java / Twitter clone / task management system ③ Add task registration function

Introduction

I would like to write an article for those who are writing applications for the first time using Java. We would appreciate it if you could use it as a reference for creating training assignments for your portfolio and company. This time, we will create a task manager. By applying this, you can also use it to create Twitter clones.

I will post articles for each function of the application.

  1. Database creation
  2. Login function
  3. Task registration function
  4. List display -Sort function -Search function
  5. Editing function
  6. Delete function
  7. Exclusive control

Execution environment

eclipse4.16.0 Tomcat9 Java11

table of contents

  1. Create view
  2. Create DAO
  3. Creating a Servlet
  4. Next notice

Create View

This is a common input form.

task-insert.jsp


<body>
<!-- header.jsp will be created last-->
<jsp:include page="header.jsp"/>
	<div class="contain">
		<h3>Task registration</h3>
<!-- task-insert-Pass each input parameter to servlet-->
		<form action="task-insert-servlet" method="post">
			<table class="form-table" border="1">
	    		<tbody>
		    		<tr>
					    <th>Task name</th>
					        <td>
					        <div class="input-key">
								<input type="text" class="form-control" name="task_name" size="60" placeholder="Please enter">
							</div>
					    </td>
				   	</tr>
			       	<tr>
			        	<th>Category</th>
			        	<td>
					        <div class="input-key">
					      		<select class="form-control" name="category_id">
			        				<option selected>Choose...</option>
			        				<option value="1">New product A: Development project</option>
			        				<option value="2">Existing product B:Improvement project</option>
			      				</select>
						    </div>
					    </td>
				    </tr>
				    <tr>
					    <th>Deadline</th>
					        <td>
					        <div class="input-key">
								<input type="date" name="limit_date" class="form-control" size="60">
							</div>
					    </td>
				   	</tr>
			        <tr>
					    <th>status</th>
				        <td>
					        <div class="input-key">
				      			<select class="form-control" name="status_code" >
				        			<option selected>Choose...</option>
				        			<option value="00">not started yet</option>
				        			<option value="50">Start</option>
				        			<option value="99">Done</option>
				     		 	</select>
				    		</div>
				        </td>
			        </tr>
			        <tr>
					    <th>Note</th>
					        <td>
					        <div class="input-key">
								<input type="text" class="form-control" name="memo" size="60">
							</div>
					    </td>
				   	</tr>
				    <tr>
				        <th><input type="submit" value="Registration" class="input-submit"></th>
				        <td></td>
			        </tr>
			    </tbody>
			</table>
	    </form>
	</div>
</body>

This is the confirmation screen when the posting is completed. Here you can see what you are posting.

task-insert-comp.jsp


<body>
<%
String task_name = (String)request.getAttribute("task_name");
int category_id = (int)request.getAttribute("category_id");
String category_name = (String)request.getAttribute("category_name");
Date limit_date = (Date)request.getAttribute("limit_date");
String status_code = (String)request.getAttribute("status_code");
String status_name = (String)request.getAttribute("status_name");
String memo = (String)request.getAttribute("memo");

%>
<jsp:include page="header.jsp"/>
	<div class="contain">
		<div class="box">
		  <h3>Task registration is complete</h3>
		  <p>I registered with the following contents</p>
		  <hr>
		  <p>
Task name:<%=task_name %><br>
Category:<%=category_id %>:<%=category_name %><br>
Deadline:<%=limit_date %><br>
status:<%=status_code %>:<%=status_name %><br>
Note:<%=memo %><br>
		  </p>
		  <a href="menu.jsp">Return to menu</a>
		</div>
	</div>
</body>

This is the display when posting fails. In particular, in the case of an input error, the location where the error occurred is displayed.

task-insert-failure.jsp


<body>
<!--The request scope error lists the reasons why the input was incorrect, so receive this.-->
<%
List<String> error = (List<String>)request.getAttribute("error");
%>
	<jsp:include page="header.jsp"/>
	<div class="contain">
		<div class="box">
		  	<h3>Failed to register the task</h3>
		  	<hr>
		  	<p>*The following causes are possible</p>
		  	<ul>
<!--Display error-->
<%for(String er : error){ %>
		  		<li><%=er %></li>
<%} %>
		  </ul>
		  <a href="task-insert.jsp">Return to registration screen</a>
		</div>
	</div>
</body>


Create DAO

First, create a method for task registration.

model.dao.TaskDAO.java


/**
	 *Method for task registration
	 * @param task_name
	 * @param category_id
	 * @param limit_date
	 * @param user_id
	 * @param status_code
	 * @param memo
	 * @return Number of executions
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	 public int insertTask(String task_name, int category_id, Date limit_date, String user_id, String status_code, String memo) throws SQLException, ClassNotFoundException {
//SQL statement input parameters and user_Create record by specifying id
		 String sql = "insert into t_task (task_name, category_id, limit_date, user_id, status_code, memo) values(?, ?, ?, ?, ?, ?)";
		 int sum = 0;
//Connect to database
		 try(Connection con = ConnectionManager.getConnection();
				 PreparedStatement pstmt = con.prepareStatement(sql)){
			 pstmt.setString(1, task_name);
			 pstmt.setInt(2, category_id);
			 pstmt.setDate(3, limit_date);
			 pstmt.setString(4, user_id);
			 pstmt.setString(5, status_code);
			 pstmt.setString(6, memo);
//Execution of update SQL statement
			 sum = pstmt.executeUpdate();
		 }
		 return sum;
	 }

The detailed explanation is the same as in the second UserDAO.java. I want to display the status name because it is easy to understand just by the status id. So let's use a method to get status_name with status_id as an argument

model.dao.StatusDAO.java


public class StatusDAO {
	/**
	 *Method to get the status name
	 * @param status_code
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public String getStatusName(String status_code) throws SQLException, ClassNotFoundException {
		String sql = "select status_name from m_status where status_code = ?";
		String status_name ="unknown";

		try(Connection con = ConnectionManager.getConnection();
				PreparedStatement pstmt = con.prepareStatement(sql)){
			pstmt.setString(1, status_code);
			ResultSet res = pstmt.executeQuery();

			while(res.next()) {
				status_name = res.getNString("status_name");
			}
		}
		return status_name;
	}
}

The detailed explanation is the same as in the second UserDAO.java. I want to display the status name because it is easy to understand only by the category Code. So let's use a method to get category_name with category_code as an argument

model.dao.CategoryDAO.java


public class CategoryDAO {
	/**
	 *Method to get the category name
	 * @param category_id
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public String getCategoryName(int category_id) throws SQLException, ClassNotFoundException {
		String sql = "select category_name from m_category where category_id = ?";
		String category_name ="unknown";

		try(Connection con = ConnectionManager.getConnection();
				PreparedStatement pstmt = con.prepareStatement(sql)){
			pstmt.setInt(1, category_id);
			ResultSet res = pstmt.executeQuery();

			while(res.next()) {
				category_name = res.getNString("category_name");
			}
		}
		return category_name;
	}

Creating a Servlet

servlet.TaskInsertServlet.java


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//DAO generation
		TaskDAO taskdao = new TaskDAO();
		CategoryDAO categorydao = new CategoryDAO();
		StatusDAO statusdao = new StatusDAO();

		//Get parameters
		request.setCharacterEncoding("UTF-8");
		String task_name = request.getParameter("task_name");
		String category_id_str = request.getParameter("category_id");
		String limit_date_check = request.getParameter("limit_date");
		String status_code = request.getParameter("status_code");
		String memo = request.getParameter("memo");

		//Get the logged-in user information from the session scope and user_Get id
		HttpSession session = request.getSession();
		String user_id = (String)session.getAttribute("current_user_id");

		//List generation to save error display
		List<String> error = new ArrayList<String>();

		//session check
		boolean sessioncheck = (boolean)session.getAttribute("login");
		if(!sessioncheck) {
			error.add("Please log in before registering the task");
		}

		//Check for input omissions
		if(task_name.equals("")) {
			error.add("The task name is blank");
		}
		if(category_id_str.equals("Choose...")) {
			error.add("No category selected");
		}
		if(status_code.equals("Choose...")) {
			error.add( "No status selected");
		}
		//Deadline (limit)_date) is special because it is a Date type
		boolean limit_check;
		limit_date_check = limit_date_check.replace('-', '/');
	    DateFormat format = DateFormat.getDateInstance();
		format.setLenient(false);
		try {
			format.parse(limit_date_check);
			 limit_check = true;
		} catch(Exception e) {
			limit_check = false;
		}
		if(!limit_check) {
			error.add("Please enter the date for the deadline");
		}

		//Save error to request scope
		request.setAttribute("error", error);

		if(task_name != "") {
			try {
				//Convert categories and deadlines (non-String type) that cannot be received according to the parameters
				int category_id = Integer.parseInt( category_id_str);
				Date limit_date = Date.valueOf(request.getParameter("limit_date"));

				//Database processing by insert method
				taskdao.insertTask(task_name, category_id, limit_date, user_id, status_code, memo);

				//Get category name / status name
				String category_name = categorydao.getCategoryName(category_id);
				String status_name = statusdao.getStatusName(status_code);

				//Save registration information in request scope
				request.setAttribute("task_name", task_name);
				request.setAttribute("category_id", category_id);
				request.setAttribute("category_name", category_name);
				request.setAttribute("limit_date", limit_date);
				request.setAttribute("status_code", status_code);
				request.setAttribute("status_name", status_name);
				request.setAttribute("memo", memo);

				RequestDispatcher rd = request.getRequestDispatcher("task-insert-comp.jsp");
				rd.forward(request, response);
			} catch(SQLException | ClassNotFoundException | IllegalArgumentException e) {
				RequestDispatcher rd = request.getRequestDispatcher("task-insert-failure.jsp");
				rd.forward(request, response);
			}
		}else {
			RequestDispatcher rd = request.getRequestDispatcher("task-insert-failure.jsp");
			rd.forward(request, response);
		}
	}

Next time preview

This time I implemented the task registration function Next time, I will try to display a list of registered tasks, add a sort function, and add a search function.

Recommended Posts

Java / Twitter clone / task management system ③ Add task registration function
Java / Twitter clone / task management system ⑥ Add deletion function
Java / Twitter clone / task management system (2) Add login function
Java / Twitter clone / task management system ④ Display task list
Java / Twitter clone / task management system (1) Create a database
Java / Twitter clone / task management system ⑥ Add deletion function
Java / Twitter clone / task management system (2) Add login function
Java / Twitter clone / task management system ③ Add task registration function
Java / Twitter clone / task management system ④ Display task list
Java / Twitter clone / task management system (1) Create a database
Java (add2)
Java (add)
Java (add2)
Java (add)