-
Database App with JDBC : 학생을 추가하는 기능 만들기 (Create)Spring 2021. 6. 19. 16:31
이번엔 학생을 학생리스트에 추가해서 저장하는 기능을 만든다.
먼저 Add new 버튼을 만들어주자.
<div id = "container"> <div id = "content"> <!-- put new button : Add Student --> <input type="button" value="Add Student" onClick="window.location.href='add-student-form.jsp'; return false;" class = "add-student-button" /> <table>
add-student-form.jsp을 만들어주자.
<!DOCTYPE html> <html> <head> <title>Add Student</title> <link type="text/css" rel="stylesheet" href = "css/style.css"> <link type="text/css" rel="stylesheet" href = "css/add-student-style.css"> </head> <body> <div id = "wrapper"> <div id = "header"> <h2>FooBar University</h2> </div> </div> <div id = "container"> <h3>Add Student</h3> <form action="StudentControllerServlet" method="GET"> <input type="hidden" name="command" value = "ADD"/> <table> <tbody> <tr> <td><label>First name : </label></td> <td><input type="text" name = "firstName" /></td> </tr> <tr> <td><label>Last name : </label></td> <td><input type="text" name = "lastName" /></td> </tr> <tr> <td><label>Email : </label></td> <td><input type="text" name = "email" /></td> </tr> <tr> <td><label></label></td> <td><input type="submit" value = "Save" class="save" /></td> </tr> </tbody> </table> </form> <div style= "clear: both;"></div> <p> <a href="StudentControllerServlet">Back to List</a> </p> </div> </body> </html>
이제 컨트롤러에 add가 작동하도록 설정하자.
route에 따라서 작동을 다르게 하도록 switch구문을 사용했고,
addStudent함수를 구현해줬다.
studentDbUtil에 addStudent라는 함수를 만들고 구현할 것이다.
package com.yunhalee.web.jdbc; import java.io.IOException; import java.util.List; import javax.annotation.Resource; 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.sql.DataSource; /** * Servlet implementation class StudentControllerServlet */ @WebServlet("/StudentControllerServlet") public class StudentControllerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private StudentDbUtil studentDbUtil; @Resource(name = "jdbc/web_student_tracker") private DataSource dataSource; @Override public void init() throws ServletException { super.init(); //create our student db util ... and pass in the conn pool / datasource try { studentDbUtil = new StudentDbUtil(dataSource); }catch(Exception exc){ throw new ServletException(exc); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //read the "command" parameter String theCommand = request.getParameter("command"); //if the command is missing, then default to listing students if(theCommand==null) { theCommand = "LIST"; } //route to the appropriate method switch(theCommand) { case "LIST": //list the students ... in MVC fashion listStudents(request, response); break; case "ADD": addStudents(request, response); break; default: listStudents(request, response); } }catch(Exception exc) { throw new ServletException(exc); } } private void addStudents(HttpServletRequest request, HttpServletResponse response) throws Exception { //read student info from form data String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); //create a new student object Student theStudent = new Student(firstName, lastName, email); //add the student to the database studentDbUtil.addStudent(theStudent); //send back to main page (the student list) listStudents(request, response); } private void listStudents(HttpServletRequest request, HttpServletResponse response) throws Exception{ //get students from db util List<Student> students = studentDbUtil.getStudent(); //add students to the request request.setAttribute("STUDENT_LIST", students); //send to JSP page (view) RequestDispatcher dispatcher = request.getRequestDispatcher("/list-students.jsp"); dispatcher.forward(request, response); } }
StudentDbUtil.java(JDBC코드)
여기서 close 할 때 Result가 없으므로 null로 넣어준다.
public void addStudent(Student theStudent) throws Exception{ // TODO Auto-generated method stub Connection myConn = null; PreparedStatement myStmt = null; try { //get db connection myConn = dataSource.getConnection(); //create sql for insert String sql = "insert into student" + "(first_name, last_name, email)" + "values (?,?,?)"; myStmt = myConn.prepareStatement(sql); //set the param values for the student myStmt.setString(1,theStudent.getFirstName()); myStmt.setString(2,theStudent.getLastName()); myStmt.setString(3,theStudent.getEmail()); //execute sql insert myStmt.execute(); } finally { //clean up JDBC objects close(myConn, myStmt, null); } } }
잘 추가된다.
db에서도 확인 가능하다
'Spring' 카테고리의 다른 글
Social Media 만들기 - 19) socket io 사용하기 ( App.js 문제 해결!) (0) 2021.08.02 Database App with JDBC : 학생 정보를 업데이트하고 삭제하는 기능 만들기 (Update, Delete) (0) 2021.06.19 Database App with JDBC : 학생 리스트 DB에서 가져오기 (Read) (0) 2021.06.18 MVC : MVC의 기본작용방법 (0) 2021.06.18 Servlets : 기본 사용 방법 (0) 2021.06.18