Seeeni Tech Diary

[Java][BE] MVC 패턴 구현 본문

컴퓨터 언어/Java

[Java][BE] MVC 패턴 구현

seyeon0207 2024. 3. 24. 23:49

0. DBUtil

  • 데이터 베이스 연결
package com.ssafy.sample.util;

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

public class DBUtil {

	private DBUtil() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	private static DBUtil instance = new DBUtil();
	public static DBUtil getInstance() {
		return instance;
	}
	
	public Connection getConnection() throws SQLException {
		String url = "jdbc:mysql://127.0.0.1:3306/schema_name?serverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8";
		String user = "user_id";
		String pwd = "user_pwd";
		return DriverManager.getConnection(url, user, pwd);
	}
	
	public void close(AutoCloseable... closeables) {
		for (AutoCloseable c : closeables) {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

1. DTO

  • Product (class)
  • path: Java Resources/dto
  • private [자료형] column
  • 생성자
  • getter, setter
  • toString
public class Product {
	private String code;
	private String model;
	private int price;

	public Product() {
		super();
	}
	
	
	public Product(String code, String model, int price) {
		super();
		this.code = code;
		this.model = model;
		this.price = price;
	}

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Product [code=" + code + ", model=" + model + ", price=" + price + "]";
	}
	
}

2. Dao

  • dao interface
  • 구현해야 하는 메소드 정의 인터페이스
public interface ProductDao {
	void create(Product product) throws Exception;
	void update(Product product) throws Exception;
	void delete(String code) throws Exception;
	Product findByCode(String code) throws Exception;
	List<Product> findAll() throws Exception;
	

}
  • dao impl → dao interface implements
  • 인터페이스로 클래스 구현
public class ProductDaoImpl implements ProductDao {
		private DBUtil db;
		private static ProductDao instance = new ProductDaoImpl();
		
		public static ProductDao getInstance() {
			return instance;
		}
	
		private ProductDaoImpl() {
			db = DBUtil.getInstance();
		}
  • DB연결
    • 생성자에서 DB연결
  • dao 싱글톤 구현
    • getInstance에서 instance 반환
	@Override
	public void create(Product product) throws Exception {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = new StringBuilder("INSERT INTO product (code, model, price)\\n")
				.append("VALUES(?,?,?)").toString();
		
		try {
			con = db.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, product.getCode());
			pstmt.setString(2, product.getModel());
			pstmt.setInt(3, product.getPrice());
			
			pstmt.executeUpdate();
		}
		finally {
			db.close(pstmt, con);
			
		}
		

	}
  • Connection con: db연결
  • PreparedStatement pstmt: sql 실행
    • pstmt.setString: n번째 ?에 값 넣어 sql 셋팅
  • findAll()
@Override
	public List<Product> findAll() throws Exception{
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet result = null;
		String sql = new StringBuilder("SELECT code, model, price\\n")
				.append("FROM Product").toString();
		
		List<Product> products = new ArrayList<>();
		
		
		try {
			con = db.getConnection();
			pstmt = con.prepareStatement(sql);
			
			result = pstmt.executeQuery();
			while(result.next()) {
				products.add(new Product(
						result.getString("code"),
						result.getString("model"),
						result.getInt("price")
						));
			}
		}
		finally {
			db.close(result, pstmt, con);
			
		}
		return products;
	}
result = pstmt.executeQuery();
while(result.next()) {
	products.add(new Product(
			result.getString("code"),
			result.getString("model"),
			result.getInt("price")
			));
}

3. Service

  • interface
public interface ProductService {
	void create(Product product) throws Exception;
	void update(Product product) throws Exception;
	void delete(String code) throws Exception;
	Product findByCode(String code) throws Exception;
	List<Product> findAll() throws Exception;
	
}
  • serviceImpl
public class ProductServiceImpl implements ProductService{
	private static ProductService instance = new ProductServiceImpl();
	private ProductDao dao;
	
	private ProductServiceImpl() {
		dao = ProductDaoImpl.getInstance();
	}
	
	public static ProductService getInstance() {
		return instance;
	}
	
	@Override
	public void create(Product product) throws Exception {
		dao.create(product);
		
	}

	@Override
	public void update(Product product) throws Exception {
		dao.update(product);
		
	}

	@Override
	public void delete(String code) throws Exception {
		dao.delete(code);
		
	}

	@Override
	public Product findByCode(String code) throws Exception {
		// TODO Auto-generated method stub
		return dao.findByCode(code);
	}

	@Override
	public List<Product> findAll() throws Exception {
		// TODO Auto-generated method stub
		return dao.findAll();
	}

}
  • 서비스를 싱글톤으로 구현
  • 생성자에서 daoimpl인스턴스 받아오기
  • dao에서 구현된 메소드들 모두 호출

4. Controller

  • servlet 만들기
public class ProductController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProductService service;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductController() {
        service = ProductServiceImpl.getInstance();
        
    }
  • service 객체 가져오기
  • action 종류에 따른 메소드 호출
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		String path = "index.jsp";
		switch(action) {
		case "list":
			path = doList(request, response);
			request.getRequestDispatcher(path).forward(request, response);
			break;
		case "home":
			response.sendRedirect(request.getContextPath() + "/index.jsp");
			break;
		case "registForm":
			response.sendRedirect(request.getContextPath() + "/product/regist.jsp");
			break;
		case "regist":
			path = doRegist(request, response);
			request.getRequestDispatcher(path).forward(request, response);
			break;
	
		case "login":
			path = doLogin(request, response);
			request.getRequestDispatcher(path).forward(request, response);
			break;
		case "logout":
			path = doLogout(request, response);
			request.getRequestDispatcher(path).forward(request, response);
			break;
		
		}
	}
  • index.jsp내 action 호출
<a href="${pageContext.request.contextPath }/product?action=list">상품 목록 페이지</a>
  • list 처리 메소드
	private String doList(HttpServletRequest request, HttpServletResponse response) {
		List<Product> products = new ArrayList<>();
		
		try {
			products = service.findAll();
			request.setAttribute("products", products);
			
			return "/product/list.jsp";
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			e.printStackTrace();
			return "/error.jsp";
		}
	}
Comments