본문 바로가기

java,jsp,spring/Spring

Spring 프로젝트 설계 - 기본 게시판

  • DAO(Data Access Object) : Database의 data에 접근을 위한 객체. Database에 접근을 하기 위한 로직과 비즈니스 로직을 분리하기 위해 사용 DB를 통해 데이터를 조회하거나 수정 삭제하는 역할
package com.javalec.spring_mvc_board.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.javalec.spring_mvc_board.dto.BDto;

public class BDao {
	DataSource dataSource;
	
	public BDao() {
		try {
			Context context = new InitialContext();
			dataSource = (DataSource)context.lookup("java:comp/env/jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public ArrayList<BDto> list(){
		ArrayList<BDto> dtos = new ArrayList<BDto>();
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = dataSource.getConnection();
			String sql = "SELECT BID, BNAME, BTITLE, BCONTENT, BDATE, BHIT FROM MVC_BOARD";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				int bId = rs.getInt("BID");
				String bName = rs.getString("BNAME");
				String bTitle = rs.getString("BTITLE");
				String bContent = rs.getString("BCONTENT");
				Timestamp bDate = rs.getTimestamp("BDATE");
				int bHit = rs.getInt("BHIT");
				
				BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit);
				dtos.add(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
		return dtos;
	}
	
	public void write(String bName, String bTitle, String bContent) {
		String sql = "INSERT INTO MVC_BOARD(BID,BNAME,BTITLE,BCONTENT,BHIT) \r\n" + 
				"VALUES(MVC_BOARD_SEQ.NEXTVAL,?,?,?,0)";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, bName);
			pstmt.setString(2, bTitle);
			pstmt.setString(3, bContent);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public BDto contentView (String strId) {
		BDto dto = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			upHit(strId);
			conn = dataSource.getConnection();
			String sql = "SELECT BID, BNAME, BTITLE, BCONTENT, BDATE, BHIT FROM MVC_BOARD WHERE BID = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(strId));
			rs = pstmt.executeQuery();
			
			if (rs.next()) {
				int bId = rs.getInt("BID");
				String bName = rs.getString("BNAME");
				String bTitle = rs.getString("BTITLE");
				String bContent = rs.getString("BCONTENT");
				Timestamp bDate = rs.getTimestamp("BDATE");
				int bHit = rs.getInt("BHIT");
				
				dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
		return dto;
	}
	
	private void upHit(String strId) {
		String sql = "UPDATE MVC_BOARD SET BHIT = BHIT+1 WHERE BID=?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(strId));
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public void modify(String bId, String bName, String bTitle, String bContent) {
		String sql = "UPDATE MVC_BOARD SET BNAME = ?, BTITLE = ?, BCONTENT = ? WHERE BID=?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, bName);
			pstmt.setString(2, bTitle);
			pstmt.setString(3, bContent);
			pstmt.setInt(4, Integer.parseInt(bId));
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
	}
public void delete(String strId) {
		String sql = "DELETE FROM MVC_BOARD WHERE BID=?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(strId));
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
	}
}
  • DTO(Data Transfer Object) : 계층 간의 데이터 교환을 위한 Java Bean
package com.javalec.spring_mvc_board.dto;

import java.sql.Timestamp;

public class BDto {
	private int bId;
	private String bName;
	private String bTitle;
	private String bContent;
	private Timestamp bDate;
	private int bHit;
	
	public BDto() {
	}
	
	public BDto(int bId, String bName, String bTitle, String bContent, Timestamp bDate, int bHit) {
		this.bId = bId;
		this.bName = bName;
		this.bTitle = bTitle;
		this.bContent = bContent;
		this.bDate = bDate;
		this.bHit = bHit;
	}

	public int getbId() {
		return bId;
	}
	public void setbId(int bId) {
		this.bId = bId;
	}
	public String getbName() {
		return bName;
	}
	public void setbName(String bName) {
		this.bName = bName;
	}
	public String getbTitle() {
		return bTitle;
	}
	public void setbTitle(String bTitle) {
		this.bTitle = bTitle;
	}
	public String getbContent() {
		return bContent;
	}
	public void setbContent(String bContent) {
		this.bContent = bContent;
	}
	public Timestamp getbDate() {
		return bDate;
	}
	public void setbDate(Timestamp bDate) {
		this.bDate = bDate;
	}
	public int getbHit() {
		return bHit;
	}
	public void setbHit(int bHit) {
		this.bHit = bHit;
	}
	
}
  • Controller : 웹에서 처리해야 할 데이터를 받고, 이 데이터를 담당할 service를 선택하여 호출 처리한 데이터를 다음 페이지에서 볼 수 있게 세팅하며, 이동할 페이지를 리턴
package com.javalec.spring_mvc_board.controller;

import javax.servlet.http.HttpServletRequest;

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

import com.javalec.spring_mvc_board.command.BCommand;
import com.javalec.spring_mvc_board.command.BListCommand;
import com.javalec.spring_mvc_board.command.BWriteCommand;

@Controller
public class BController {
	BCommand command;
	
	@RequestMapping("/list")
	public String list(Model model) {
		System.out.println("=======> list()");
	
		// command 단 호출
		command = new BListCommand();
		// command 인터페이스에서 메소드들을 상속하기 때문에 클래스를 많이 만들어도 command 인터페이스로 받으면 편리함
		command.execute(model);
		return "list";
	}
	@RequestMapping("/write_view")
	public String write_view() {
		System.out.println("=======> write_view()");
		return "write_view";
	}
	@RequestMapping("/write")
	public String write(HttpServletRequest request, Model model) {
		System.out.println("=======> write()");
		
		model.addAttribute("request", request);
		// comand 단의 map.get("")의 이름과 같아야함.
		command = new BWriteCommand();
		command.execute(model);
		
		return "redirect:list";
		// insert를 할 것이기 때문에 write는 만들지 않고 list로 이동
	}
@RequestMapping("/content_view")
	public String content_view(HttpServletRequest request, Model model) {
		System.out.println("=======> content_view()");
		
		model.addAttribute("request", request);
		command = new BContentCommand();
		command.execute(model);
		
		return "content_view";
	}
	@RequestMapping("/modify")
	public String modify(HttpServletRequest request, Model model) {
		System.out.println("=======> modify()");
		
		model.addAttribute("request", request);
		command = new BModifyCommand();
		command.execute(model);
		
		return "redirect:list";
		// 글 수정 후 list로 이동
	}
@RequestMapping("/delete")
	public String delete(HttpServletRequest request, Model model) {
		System.out.println("=======> delete()");

		model.addAttribute("request", request);
		command = new BDeleteCommand();
		command.execute(model);
		
		return "redirect:list";
		// 글 삭제 후 list로 이동
	}
}
  • Service : 데이터를 dao를 통해 주고받으면서 비즈니스 로직을 수행, Client가 요청할 양식과 요청을 처리하는 과정에서 기준이 되는 틀을 정의
package com.javalec.spring_mvc_board.command;

import org.springframework.ui.Model;

public interface BCommand {
	public void execute(Model model);
}
// Interface 생성
-------------------------------------------------------------
package com.javalec.spring_mvc_board.command;

import java.util.ArrayList;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;
import com.javalec.spring_mvc_board.dto.BDto;

public class BListCommand implements BCommand{

	@Override
	public void execute(Model model) {
		//dao 단 호출
		BDao dao = new BDao();
		ArrayList<BDto> dtos = dao.list();
		model.addAttribute("list", dtos);
	}
	
}
// Interface를 상속 받은 클래스 생성
-------------------------------------------------------------
package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;

public class BWriteCommand implements BCommand {
	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		
		String bName = request.getParameter("bName");
		String bTitle = request.getParameter("bTitle");
		String bContent = request.getParameter("bContent");
		
		BDao dao = new BDao();
		dao.write(bName, bTitle, bContent);
	}
}
// 글쓰기 클래스 생성
-------------------------------------------------------------
package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;
import com.javalec.spring_mvc_board.dto.BDto;

public class BContentCommand implements BCommand {

	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		String bId = request.getParameter("bId");
		
		BDao dao = new BDao();
		BDto dto = dao.contentView(bId);
		model.addAttribute("content_view", dto);
	}
}
// 글 내용 보는 클래스 생성
-------------------------------------------------------------
package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;

public class BModifyCommand implements BCommand {

	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		
		String bId = request.getParameter("bId");
		String bName = request.getParameter("bName");
		String bTitle = request.getParameter("bTitle");
		String bContent = request.getParameter("bContent");
		
		BDao dao = new BDao();
		dao.modify(bId, bName, bTitle, bContent);
	}
}
// 글 수정하는 클래스 생성
-------------------------------------------------------------
package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;

public class BDeleteCommand implements BCommand  {

	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		String bId = request.getParameter("bId");
		
		BDao dao = new BDao();
		dao.delete(bId);
	}
}
// 글 삭제하는 클래스 생성

 

  • JSP 페이지
// list.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<table width="500" border="1">
		<tr>
			<th>번호</th>
			<th>이름</th>
			<th>제목</th>
			<th>날짜</th>
			<th>조회수</th>
		</tr>
		<c:forEach items="${list }" var="dto">
			<tr>
				<td>${dto.bId }</td>
				<td>${dto.bName }</td>
				<td>${dto.bTitle }</td>
				<td>${dto.bDate }</td>
				<td>${dto.bHit }</td>
			</tr>
		</c:forEach>
		<tr>
			<td colspan="5">
				<a href="write_view">글작성</a>
			</td>
		</tr>
	</table>
</body>
</html>
// write_view.jsp
<body>
	<table width="500" border="1">
		<form method="post" action="write">
			<tr>
				<td>이름</td>
				<td>
					<input type="text" name="bName" size="50" />
				</td>
			</tr>
			<tr>
				<td>제목</td>
				<td>
					<input type="text" name="bTitel" size="50" />
				</td>
			</tr>
			<tr>
				<td>내용</td>
				<td>
					<textarea rows="10" name="bContent"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="입력" />
				</td>
			</tr>
		</form>
	</table>
</body>
// content_view
<body>
	<form method="post" action="modify">
		<input type="hidden" name="bId" value="${content_view.bId}" />
		<table width="500" border="1">
			<tr>
				<td>번호</td>
				<td>${content_view.bId}</td>
			</tr>
			<tr>
				<td>조회수</td>
				<td>${content_view.bHit}</td>
			</tr>
			<tr>
				<td>작성자</td>
				<td>
					<input type="text" name="bName" value="${content_view.bName}" />
				</td>
			</tr>
			<tr>
				<td>제목</td>
				<td>
					<input type="text" name="bTitle" value="${content_view.bTitle}" />
				</td>
			</tr>
			<tr>
				<td>내용</td>
				<td>
					<input type="text" name="bContent" value="${content_view.bContent}" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="수정">
					&nbsp;&nbsp;
					<a href="list">목록</a>
					&nbsp;&nbsp;
					<a href="delete?bId=${content_view.bId}">삭제</a>
				</td>
			</tr>
		</table>
	</form>
</body>

'java,jsp,spring > Spring' 카테고리의 다른 글

Spring 로그인 페이지 설계  (0) 2022.10.14
STS 한글 깨짐 현상 해결  (0) 2022.10.14
Spring 기초 (5)  (0) 2022.10.11
Spring 기초 (4)  (0) 2022.10.11
Spring 기초 (3)  (0) 2022.10.05