공부/[Project] 치킨
리스트를 보여주는 기능
맴썰
2021. 12. 23. 19:34
DB 상에 등록되어 있는 치킨의 목록을 나타내는 기능을 구현하였다.
CREATE TABLE Chicken(
code NUMBER GENERATED ALWAYS AS IDENTITY primary key,
name varchar2(100) not null unique,
price integer not null
);
<Chicken.SQL>
기본키를 자동생성함으로써 겹치는 일이 없도록 만들었다.
package vo;
public class Chicken {
private String code;
private String name;
private int price;
public Chicken(String b, int c){this.name = b; this.price = c;}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
VO file을 만들고 getter와 Setter를 설정해주었다.
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에서 리스트 로딩함수와 치킨 등록 함수를 선언하였다.
Spring framework의 Autowired annotation을 사용하고 싶었는데 잘 안되어서 그냥 객체를 선언했다.
package service;
import static com.smc.db.JdbcUtil.*;
import java.sql.Connection;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import vo.Chicken;
import dao.ChicDAO;
@Service
public class ChickenListService {
public ChicDAO chicDAO = new ChicDAO();
public ArrayList<Chicken> getChickenList(){
chicDAO = ChicDAO.getInstance();
Connection con = getConnection();
chicDAO.setConnection(con);
return chicDAO.selectCList();
}
}
서비스 클래스는 DAO객체에 Connection 객체를 넣어주고, DB로부터 ArrayList 형태의 치킨 정보를 받아오는 역할을 수행한다.
package com.smc.test;
import vo.Chicken;
import service.ChickenListService;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ChickenListController {
@Autowired
private ChickenListService chickenListService;
@RequestMapping("/CList.chic")
public ModelAndView view(HttpServletRequest request) {
ArrayList<Chicken> temp = chickenListService.getChickenList();
try {
request.setAttribute("chic", temp);
}catch(Exception e) {
e.printStackTrace();
}
ModelAndView mav = new ModelAndView();
mav.setViewName("/CList");
return mav;
}
}
컨트롤러 클래스는 브라우저가 사용자의 경로에 있는 View에 도달할 수 있게 해주는 역할을 수행하며 사용자의 요청을 받고, 응답하는 역할을 수행한다. 나는 ArrayList를 HttpServletRequest 객체에 저장했다.
<%@ page import = "vo.Chicken"%>
<%@ page import = "java.util.ArrayList"%>
<%@ 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>
<%
ArrayList<Chicken> clist = (ArrayList<Chicken>)request.getAttribute("chic");
%>
</head>
<body>
<h3>치킨 목록 </h3>
<table style="1px solid black; width:30%; height:100px; margin : auto; text-align = center";>
<tr>
<td>이름</td>
<td>가격</td>
</tr>
<%
if(clist!=null){
for(int i=0; i<clist.size();i++){
%>
<form action = "/test/CReview.chic"><tr>
<td><% String name = clist.get(i).getName(); out.println(name); %></td>
<td><%=clist.get(i).getPrice() %></td>
<td><button type = "submit" onclick = "location.href ='CReview.chic'" name = "name" value = "<%=name%>" formmethod = "get">리뷰 쓰기</button></td>
</tr>
</form>
<%
}
} else{
%>
<tr><td colspan="2"> 등록된 치킨이 없습니다. </td></tr>
<%
}
%>
</table>
</body>
</html>
컨트롤러에서 보낸 ArrayList를 받아 View로 뿌려주는 역할을 수행하는 뷰 페이지이다.
위와 같이 DB에 있는 내용을 잘 보여준다.