본문 바로가기
공부/[Project] 치킨

새로운 치킨을 등록하는 기능

by 맴썰 2021. 12. 23.
package dao;

import static com.smc.db.JdbcUtil.*;




import java.sql.*;
import java.util.ArrayList;
import org.springframework.stereotype.Repository;


import vo.Chicken;

@Repository
public class ChicDAO 
{
	Connection con;
	private static ChicDAO cDAO;
	
	
	public void setConnection(Connection con) { this.con = con;}
	
	public static ChicDAO getInstance() {
		if(cDAO==null) cDAO = new ChicDAO();
		return cDAO;
	}
	
	public ArrayList<Chicken> selectCList(){
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList<Chicken> CList = null;
		try {
			pstmt = con.prepareStatement("SELECT * FROM chicken");
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				CList = new ArrayList<>();
				do {
					CList.add(new Chicken(rs.getString("name"),rs.getInt("price")));
				} while(rs.next());
			}
		} catch(SQLException e) {
			e.printStackTrace();
		}finally {close(rs); close(pstmt);}
		
		return CList;
	}
	
	public int insertChicken(Chicken chic) {
		PreparedStatement pstmt = null;
		int insertCount = 0;
		String Sql = "";
		
		try {
			Sql = "INSERT INTO Chicken(name,price) VALUES(?,?)";
			pstmt = con.prepareStatement(Sql);
			pstmt.setString(1, chic.getName());
			pstmt.setInt(2, chic.getPrice());
			insertCount = pstmt.executeUpdate();
		}catch(SQLIntegrityConstraintViolationException e){
			System.out.println("이미 같은 정보가 있습니다.");
			return -1;
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {close(pstmt);}
		
		return insertCount;
	}
}

DAO file에서 insert 함수를 정의했다. 무결성 오류는 따로 확인하기 위해서 SQLIntegrityConstraintViolationException을 SQLException 상위에서 처리하였다.

 


package service;
import static com.smc.db.JdbcUtil.*;


import java.sql.Connection;
import vo.Chicken;
import dao.ChicDAO;


public class ChickenInsertService {
	public ChicDAO chicDAO = new ChicDAO();

	public int insertChicken(Chicken chic) {
		chicDAO = ChicDAO.getInstance();
		Connection con = getConnection();
		chicDAO.setConnection(con);
		int cnt = chicDAO.insertChicken(chic);
		int isSuccess = 0;
		if(cnt>0) {commit(con); isSuccess = 1;}
		else if(cnt==-1) {return -1;}
		else rollback(con);
		close(con);
		return isSuccess;
	}
}

서비스 클래스에서는 마찬가지로 DB 연결 후 DAO객체에 할당한 후 insert를 실행하고 결과를 반환하는 역할을 수행한다.

 


package com.smc.test;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class ChickenInsertController {

	@RequestMapping(value = "/CInsert.chic" , method = RequestMethod.GET)
	public String view(HttpServletRequest request ,Model model) {
		String result = "CInsert";
			return result;

	}
}

insert 작업은 JSP file에서 진행하므로 controller에서는 특별한 작업을 수행하지 않는다.

 


<%@ page import = "vo.Chicken" %>
<%@ page import = "service.ChickenInsertService" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>치킨 정보 등록</title>
</head>
<body>
<form class = "Chic-regist" action = "/test/CInsert.chic" method = "get">
 	이름 : <input type="text" name = "name" required = "required"><br>
 	가격 : <input type="text" name = "price" required = "required"><br>
 	<button class = "btn" type = "submit">등록</button>
 </form>
 
  <a href= "CList.chic">치킨 목록</a>
 
 <%
 	String name = request.getParameter("name");
 	String price = request.getParameter("price");
 	
 		if(name!=null){
 			Chicken chic = new Chicken(name, Integer.parseInt(price));
 			ChickenInsertService cis = new ChickenInsertService();
 			int iS = cis.insertChicken(chic);
 			if(iS==1) out.println("등록 완료되었습니다.");
 			else if(iS==-1){out.println("이미 등록되어있는 치킨입니다.");}
 			else out.println("등록에 실패하였습니다.");
 		}
 	
 %>
</body>
</html>

form 태그에서 get 방식으로 넘어온 값들을 jsp file 내에서 받아 DB에 insert한다.

insertChicken의 반환 값이 -1인 경우는 SQLIntegrityConstraintViolationException이 발생한 경우이다.

 


데이터를 입력한 모습
등록 버튼을 누르면 위와 같이 치킨이 등록된다.