Java/JSP

JSP 기초(DB 연결) - AWS 풀스택 과정 61일차

awspspgh 2024. 10. 22. 17:49
목차
1. 설정
2. DB 연결

 

1. 설정

mvnrepository 사이트에서 검색하여 jar 다운로드
log4j2.jar - 콘솔에 로그를 찍을 때 사용하는 라이브러리
- log4j2-api-2.18.0 => 2.20.0
- log4j2-core
- log4j2-slf4j-impl 2.0.09 ~ 2.0.16
- log4j2-web
- slf4j-api-1.7.36 => 1.7.36
mysql-connector-j -> db 연결 커넥터
mybatis-3.5.10 -> db의 처리를 도와주는 라이브러리

jar 다운로드

 

D드라이브에 새 파일 생성 후 switch workspace

- encoding 설정

 

- utf-8 확인

 

- Installed JREs, compiler, Tomcat server 설정

 

- console size, web Browser 설정

 

- Show Views(Package Explorer, Servers, Console) 설정

 

- web.xml ports 설정

더블 클릭

 

- path 간략화

 

2. DB 연결

- 파일 이동

다운로드했던 파일들 모두 ctrl C, ctrl V

 

- create Servlet할 때

Next >

 

 

 

 

▣ web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>jsp_study</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </context-param>
  <context-param>
  	<param-name>log4jConfig</param-name>
  	<param-value>/WEB-INF/log4j2.xml</param-value>
  </context-param>
</web-app>

 

▣ index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Welcome to JSP world~!!</h1>
	<!-- jsp의 모든 경로는 controller로 이동되게 해야함. -->
	<h3><a href="/brd/register">board 글쓰기 페이지로 이동</a></h3>
	<h3><a href="/brd/list">board 리스트 페이지로 이동</a></h3>
</body>
</html>

 

▣ log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status = "INFO">
	<Appenders>
		<Console name = "console" target="SYSTEM_OUT">
			<PatternLayout pattern = "%d - %m%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Root level="INFO">
			<AppenderRef ref = "console" />
		</Root>
	</Loggers>
</Configuration>

 

▣ sqlFile.sql

create table board(
  bno int auto_increment,
  title varchar(500) not null,
  writer varchar(100) not null,
  content text,
  regdate datetime default now(),
  moddate datetime default now(),
  primary key(bno));

 

▣ BoardVO.java

package domain;

public class BoardVO {
	private int bno;
	private String title;
	private String writer;
	private String content;
	private String regdate;
	private String moddate;
	
	public BoardVO() {}

	// insert : title, writer, content
	public BoardVO(String title, String writer, String content) {
		this.title = title;
		this.writer = writer;
		this.content = content;
	}

	// list : bno, title, writer, regdate
	public BoardVO(int bno, String title, String writer, String regdate) {
		this.bno = bno;
		this.title = title;
		this.writer = writer;
		this.regdate = regdate;
	}

	// update : bno, title, content
	public BoardVO(int bno, String title, String content) {
		super();
		this.bno = bno;
		this.title = title;
		this.content = content;
	}

	// detail : 전부
	public BoardVO(int bno, String title, String writer, String content, String regdate, String moddate) {
		super();
		this.bno = bno;
		this.title = title;
		this.writer = writer;
		this.content = content;
		this.regdate = regdate;
		this.moddate = moddate;
	}

	public int getBno() {
		return bno;
	}

	public void setBno(int bno) {
		this.bno = bno;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getWriter() {
		return writer;
	}

	public void setWriter(String writer) {
		this.writer = writer;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getRegdate() {
		return regdate;
	}

	public void setRegdate(String regdate) {
		this.regdate = regdate;
	}

	public String getModdate() {
		return moddate;
	}

	public void setModdate(String moddate) {
		this.moddate = moddate;
	}

	@Override
	public String toString() {
		return "BoardVO [bno=" + bno + ", title=" + title + ", writer=" + writer + ", content=" + content + ", regdate="
				+ regdate + ", moddate=" + moddate + "]";
	}

}

 

▣ BoardController.java

package controller;

import java.io.IOException;
import java.util.List;

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import domain.BoardVO;
import service.BoardService;
import service.BoardServiceImpl;


@WebServlet("/brd/*")
public class BoardController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 로그 객체 생성
	private static final Logger log = LoggerFactory.getLogger(BoardController.class);
    // jsp에서 받은 요청을 처리, 그 결과를 다른 jsp로 보내는 역할을 하는 객체
	private RequestDispatcher rdp;
	private String destPage; // 응답할 jsp의 주소를 저장하는 변수
	private int isOk; // db 구문 체크값 저장 변수
	private BoardService bsv; // interface로 생성(service package에)
 
    public BoardController() {
    	// 생성자
    	bsv = new  BoardServiceImpl(); // class로 생성(service package에) bsv 구현체 연결
    }


	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 실제 get post 요청처리
		log.info("log 객체 test");
		
		// request, response 객체의 인코딩 설정
		request.setCharacterEncoding("utf-8"); // 요청 객체
		response.setCharacterEncoding("utf-8"); // 응답 객체
		// response는 jsp로 갈 응답 객체 => 화면을 생성해서 응답 => jsp 형식으로...
		// contentType="text/html; charset=UTF-8"
		response.setContentType("text/html; charset=UTF-8"); // html5 형식으로 보내라
		
		// 경로 가져오기 /brd/register
		String uri = request.getRequestURI();
		log.info(uri); // /brd/register
		
		String path = uri.substring(uri.lastIndexOf("/")+1);
		log.info(path);
		
		switch(path) {
		case "register": 
			// 정보가 필요하다면... 정보를 DB에서 요청 request 객체 살고 보내기
			destPage = "/board/register.jsp";
			break;
		case "insert":
			try {
				log.info("insert case in~!!");
				// jsp 화면에서 보내온 파라미터 값을 저장 => Service 전송
				String title = request.getParameter("title");
				String writer = request.getParameter("writer");
				String content = request.getParameter("content");
				BoardVO bvo = new BoardVO(title, writer, content);
				log.info(">>>>> bvo insert 객체 >>>>> {}", bvo);
				
				isOk = bsv.register(bvo);
				log.info(">>> bco insert"+(isOk > 0 ? "성공":"실패"));
				
				// 처리 후 목적지
				destPage="/index.jsp";
				
			} catch (Exception e) {
				log.info("insert error!!");
				e.printStackTrace();
			}
			break;
		case "list": 
			try {
				// 전체 리스트를 가지고 list.jsp로 전달
				List<BoardVO> list = bsv.getList();
				log.info(">>> list >>> {}", list);
				// request 객체에 파라미터로 값을 보내는 방법
				request.setAttribute("list", list);
				destPage = "/board/list.jsp";
			} catch (Exception e) {
				log.info("list error!!");
				e.printStackTrace();
			}
			break;
		case "detail": case "modify":
			try {
				int bno = Integer.parseInt(request.getParameter("bno"));
				BoardVO bvo = bsv.getDetail(bno);
				log.info(">>>>> degail bvo >>>>> {}", bvo);
				request.setAttribute("bvo", bvo);
//				if(path.equals("detail")) {
//					destPage = "/board/detail.jsp";
//				}else {
//					destPage = "/board/modify.jsp";					
//				}
				destPage = "/board/"+path+".jsp";
			} catch (Exception e) {
				log.info(""+path+"error!!");
				e.printStackTrace();
			}
			break;
		case "update":
			try {
				int bno = Integer.parseInt(request.getParameter("bno"));
				String title = request.getParameter("title");
				String content = request.getParameter("content");
				BoardVO bvo = new BoardVO(bno, title, content);
				int isOk = bsv.update(bvo);
				log.info(">>>>> update >>>>>" +(isOk>0 ? "성공":"실패"));
				// 컨트롤러 내부 케이스는 /brd/ 따로 적을 필요가 없음
				destPage="detail?bno="+bno;
			}catch (Exception e) {
				log.info("update error!!");
				e.printStackTrace();
			}
			break;
		case "delete":
			try {				
				int bno = Integer.parseInt(request.getParameter("bno"));
				int isOk = bsv.delete(bno);
				log.info(">>>>> delete >>>>>" +(isOk>0 ? "성공":"실패"));
				destPage="list";
			} catch(Exception e){
				log.info("delete error!!");
				e.printStackTrace();
			}
			break;
		}
		
		// 목적지 주소(destPage)로 데이터를 전달(RequestDispatcher)
		rdp = request.getRequestDispatcher(destPage);
		// 요청에 필요한 객체를 가지고 destPage에 적힌 경로로 이동
		rdp.forward(request, response);
		
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// get으로 들어오는 요청을 처리하는 메서드 => service를 호출하여 처리
		service(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// post로 들어오는 요청을 처리하는 메서드 => service를 호출하여 처리
		service(request, response);
	}

}

 

- Logger 에러시, Import 'Logger'(org.slf4j) 클릭

 

▣ BoardService.java

package service;

import java.util.List;

import domain.BoardVO;

public interface BoardService {
 	
	int register(BoardVO bvo);

	List<BoardVO> getList();

	BoardVO getDetail(int bno);

	int update(BoardVO bvo);

	int delete(int bno);
	
}

 

▣ BoardServiceImpl.java

package service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dao.BoardDAOImpl;
import dao.BoardDao;
import domain.BoardVO;

public class BoardServiceImpl implements BoardService {
	private static final Logger log = LoggerFactory.getLogger(BoardServiceImpl.class);
	// dao 연결
	private BoardDao bdao;
	
	public BoardServiceImpl() {
		bdao = new BoardDAOImpl();
	}
	
	@Override
	public int register(BoardVO bvo) {
		log.info(">>>>> register service in");
		return bdao.insert(bvo);
	}

	@Override
	public List<BoardVO> getList() {
		// TODO Auto-generated method stub
		return bdao.getList();
	}

	@Override
	public BoardVO getDetail(int bno) {
		// TODO Auto-generated method stub
		return bdao.getDetail(bno);
	}

	@Override
	public int update(BoardVO bvo) {
		// TODO Auto-generated method stub
		return bdao.update(bvo);
	}

	@Override
	public int delete(int bno) {
		// TODO Auto-generated method stub
		return bdao.delete(bno);
	}
}

 

▣ BoardDao.java

package dao;

import java.util.List;

import domain.BoardVO;

public interface BoardDao {

	int insert(BoardVO bvo);

	List<BoardVO> getList();

	BoardVO getDetail(int bno);

	int update(BoardVO bvo);

	int delete(int bno);

}

 

▣ BoardDaoImpl.java

package dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import domain.BoardVO;
import orm.DatabaseBuilder;


public class BoardDAOImpl implements BoardDao {
	private static final Logger log = LoggerFactory.getLogger(BoardDAOImpl.class);
	// DB와 연결 => mybatis 사용하여 연결 (mybatisConfig, db연결클래스, mapper)
	
	// DB의 연결을 위한 객체
	private SqlSession sql;
	
	public BoardDAOImpl() {
		new DatabaseBuilder();
		sql = DatabaseBuilder.getFactory().openSession();
	}
	
	@Override
	public int insert(BoardVO bvo) {
		// mapper로 연결
		log.info(">>>> insert DAO in!!");
		// sql.insert(mapper의 namespace.id, 객체);
		// insert / update / delete 구문은 commit 필요
		int isOk = sql.insert("BoardMapper.add", bvo);
		if(isOk > 0) {
			sql.commit();
		}
		return isOk;
	}

	@Override
	public List<BoardVO> getList() {
		log.info(">>>> getList DAO in!!");
		return sql.selectList("BoardMapper.list");
	}

	@Override
	public BoardVO getDetail(int bno) {
		log.info(">>>>> getDetail DAO in!!");
		return sql.selectOne("BoardMapper.detail", bno);
	}

	@Override
	public int update(BoardVO bvo) {
		log.info(">>>>> update DAO in!!");
		int isOk = sql.update("BoardMapper.up", bvo);
		if(isOk > 0) sql.commit();
		return isOk;
	}

	@Override
	public int delete(int bno) {
		// TODO Auto-generated method stub
		int isOk = sql.delete("BoardMapper.del", bno);
		if(isOk > 0) sql.commit();
		return isOk;
	}
}

 

▣ mybatisConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/javadb"/>
        <property name="username" value="javaUser"/>
        <property name="password" value="mysql"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="mapper/boardMapper.xml"/>
  </mappers>
</configuration>

 

- mybatisConfig 오류 시 설정

 

▣ boardMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="BoardMapper">
	<!-- namespace는 daoImpl <-> mapper를 연결하기 위한 이름 -->  
	<!-- sql별 id를 생성하여 id를 통해 daoImpl이 어떤 sql 구문을 실행하는지 인지 id는 중복불가 -->
	<!-- parameterType = 매개변수의 객체타입(생략가능), resultType = 결과로 나가는 객체 -->
	<!-- 실제 SQL 구문사용 -->
	<insert id = "add" parameterType="domain.BoardVO">
	insert into board(title, writer, content)
	values(#{title}, #{writer}, #{content})
	</insert>
	
	<select id="list" resultType="domain.BoardVO">
		select * from board order by bno desc
	</select>
	
	<select id="detail" parameterType="int" resultType="domain.BoardVO">
		select * from board where bno = #{bno}
	</select>
	
	<update id="up" parameterType="domain.BoardVO">
		update board set title = #{title}, content = #{content}, moddate = now() where bno = #{bno}
	</update>
	
	<delete id="del" parameterType="int">
		delete from board where bno = #{bno}
	</delete>
	
  </mapper>

 

▣ DatabaseBuilder.java

package orm;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DatabaseBuilder {
	private static SqlSessionFactory factory;
	private static final String CONFIG = "orm/mybatisConfig.xml";
	
	// 초기화 블럭을 사용하여 객체 생성 후 초기화
	static {
		try {
			factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(CONFIG));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSessionFactory getFactory() {
		return factory;
	}

}

 

▣ register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Board Register Page</h1>
	<!-- 등록은 / 수정 post -->
 	<form action = "/brd/insert" method="post">
		title: <br>
		<input type="text" name="title" placeholefer="제목..."><br>
		writer: <br>
		<input type="text" name="writer" placeholder = "작성자..."><br>
		content: <br>
		<textarea rows="10" cols="50" name="content" placeholder="내용을 입력하세요."></textarea><br>
		<button type="submit">등록</button>
 	</form>
</body>
</html>

 

▣ list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Board List Page</h1>
	<table>
		<thead>
			<tr>
				<th>no.</th>
				<th>title</th>
				<th>writer</th>
				<th>regdate</th>
			</tr>
		</thead>
		<tobody>
			<c:forEach items="${list }" var="bvo">
				<tr>
					<td>${bvo.bno }</td>
					<td><a href="/brd/detail?bno=${bvo.bno }">${bvo.title }</a></td>
					<td>${bvo.writer }</td>
					<td>${bvo.regdate }</td>
				</tr>
			</c:forEach>
		</tobody>
	</table>
</body>
</html>

 

▣ detail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Board Detail Page</h1>
	<table>
		<thead>
			<tr>
				<th>no.</th>
				<th>title</th>
				<th>writer</th>
				<th>content</th>
				<th>regdate</th>
				<th>moddate</th>
			</tr>
		</thead>
		<tobody>
			<tr>
				<td>${bvo.bno }</td>
				<td>${bvo.title }</td>
				<td>${bvo.writer }</td>
				<td>${bvo.content }</td>
				<td>${bvo.regdate }</td>
				<td>${bvo.moddate }</td>
			</tr>
		</tobody>
	</table>
				<button type="submit">수정</button>
				<button type="submit">삭제</button>
</body>
</html>

 

▣ modify.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Board Modify Page</h1>
	<form action="/brd/update" method="post">
	<input type="hidden" name="bno" value="${bvo.bno }">
	<table>
		<thead>
			<tr>
				<th>no.</th>
				<td>${bvo.bno }</td>
			</tr>
			<tr>
				<th>title</th>
				<td> <input type="text" name="title" value="${bvo.title }"> </td>
			</tr>
			<tr>
				<th>writer</th>
				<td>${bvo.writer }</td>
			</tr>
			<tr>
				<th>regdate</th>
				<td>${bvo.regdate }</td>
			</tr>
			<tr>
				<th>moddate</th>
				<td>${bvo.moddate }</td>
			</tr>
			<tr>
				<th>content</th>
				<td> <textarea rows="10" cols="50" name="content">${bvo.content }</textarea> </td>
			</tr>
		</thead>
	</table>
	<!-- 수정버튼을 누르면 내가 수정한 내용을 가지고(form => submit) 컨트롤러로 이동 -->	
	<button type="submit">modify commit</button>
	<!-- 리스트 버튼을 누르면 리스트페이지로 이동 -->
	<a href="/brd/list"><button type="button">list</button></a>
	</form>
</body>
</html>

 

▷ 출력

등록 및 리스트

 

수정 및 삭제