Eggs Sunny Side Up
본문 바로가기
Web/JSP_Servlet

MVC_게시글 작성, 게시글 조회 by FrontController

by guswn100059 2023. 5. 3.

기본 설계

sql

db에 파일을 저장할 때 이미지 자체로 저장하기엔 용량이 너무 크기에

이미지 저장경로를 업로드한다.

그렇기에 이미지를 받는 열은 varchar2()로 작성해줌.

-- 회원 정보 테이블 만들기
create table Member
(
   email varchar2(100),
   pw varchar2(100) not null,
   tel varchar2(100),
   address varchar2(100),
   
   constraint member_email_pk primary key(email)

);

select * from Member;

-- board 테이블
create table web_board(
	num number primary key,
	title varchar2(100),
	writer varchar2(100),
	filename varchar2(200),
	content varchar2(100),
	b_date date
);

select * from web_board;

-- num 컬럼에 들어갈 시퀀스 생성 : num_board
create sequence num_board
increment by 1
start with 1;

commit;

-- test
insert into web_board 
values (num_board.nextval, 'test', '현주', 'test', 'test', sysdate);

insert into web_board
values(num_board.nextval, 'test1', '수모킹', 'test1', 'test1', sysdate);

 

boardMain.jsp

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
		<title>Forty by HTML5 UP</title>
		<meta charset="utf-8" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
		<link rel="stylesheet" href="assetsBoard/css/main.css" />
		<link rel="stylesheet" href="assetsBoard/css/board.css" />
		<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
		<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
		
</head>
<body>		
		
			<div id="board">
				<table id = "list">
					<tr>
						<td>번호</td>
						<td>제목</td>
						<td>작성자</td>
						<td>시간</td>
					</tr>
				
				</table>
				
				<a href="goMain.do"><button id="writer">홈으로가기</button></a>
				<a href="goWriterBoard.do"><button id="writer">작성하러가기</button></a>
			</div>


			<!-- Scripts -->
			<script src="assets/js/jquery.min.js"></script>
			<script src="assets/js/jquery.scrolly.min.js"></script>
			<script src="assets/js/jquery.scrollex.min.js"></script>
			<script src="assets/js/skel.min.js"></script>
			<script src="assets/js/util.js"></script>
			<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
			<script src="assets/js/main.js"></script>
</body>
</html>

 

writerBoard.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
		<title>Forty by HTML5 UP</title>
		<meta charset="UTF-8" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
		<link rel="stylesheet" href="assetsBoard/css/main.css" />
		<link rel="stylesheet" href="assetsBoard/css/board.css" />
		<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
		<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
</head>
<body>

			<div id = "board">
				<!-- 
					enctype : 기본값 => application/x-www-form-urlencoded
								    => Key값과 Value 형태로 데이터 전송
							: 파일 업로드 시 => multipart/form-date 
										  => 이미지 등과 같은 용량이 큰 데이터 전송
				 -->
				<form action="writeBoard.do" method="post" enctype="multipart/form-data">
				<table id="list">
					<tr>
						<td>제목</td>
						<td><input type="text" name="title"> </td>
					</tr>
					<tr>
						<td>작성자</td>
						<td><input  type="text" name="writer"> </td>
					</tr>
					<tr>
						<td colspan="2">내용</td>
					</tr>
					<tr>
						<td colspan="2">
							<input  type="file" style="float: right;" name="filename">
							<textarea  rows="10" style="resize: none;" name="content"></textarea>			
						</td>
					</tr>
					<tr>
						<td colspan="2">
							<input type="reset" value="초기화">
							<input type="submit" value="작성하기">
						</td>
					</tr>
				</table>
				</form>
			</div>
			<!-- Scripts -->
			<script src="assets/js/jquery.min.js"></script>
			<script src="assets/js/jquery.scrolly.min.js"></script>
			<script src="assets/js/jquery.scrollex.min.js"></script>
			<script src="assets/js/skel.min.js"></script>
			<script src="assets/js/util.js"></script>
			<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
			<script src="assets/js/main.js"></script>
</body>
</html>

 

WriteBoardController

package kr.smhrd.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class WriteBoardController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 1) 데이터 수집
		// post방식 인코딩
		request.setCharacterEncoding("UTF-8");
		
		// 1. 모든 요청 정보가 들어있는 request 객체
		// 2. 업로드 된 파일(이미지)을 저장할 경로(DB에 이미지를 저장X, 경로만 저장O)
		// "C:/users/..." 해당 경로는 에러가 날 확률이 높음
		// ∵ Linux는 "home/~", Window "C:/~"로 경로가 저장되기 때문에 
		//	 아래와 같은 코드를 사용
		String path = request.getServletContext().getRealPath("file");
		
		System.out.println(path);
		
		// 3. 파일의 max size (단위 : byte)
		int maxSize = 10*1024*1024; // 10MB(1MB=1024byte)
		
		// 4. 인코딩 방식
		String encoding = "UTF-8";
		
		// 5. 파일이름 중복제거 => 파일명 뒤에 숫자를 붙여주는 객체
		DefaultFileRenamePolicy rename = new DefaultFileRenamePolicy();
		
		// 파일 업로드 => MultipartRequest
		// 필요한 라이브러리 => cos.jar
		MultipartRequest multi = new MultipartRequest(request, path, maxSize, encoding, rename);
		
		// DB에 저장하기 위해서 게시글 정보 가져오기
		String title = multi.getParameter("title");
		String writer = multi.getParameter("writer");
		String content = multi.getParameter("content");
		
		// 우리가 파일의 이름을 가져올 때 save
		String filename = multi.getFilesystemName("filename");
		
		System.out.println(title);
		System.out.println(writer);
		System.out.println(filename);
		System.out.println(content);
		
		// 2) 기능 구현
		// 게시글 작성 => web_board 테이블에 게시글 데이터를 저장하겠다.
		// 1. DTO/VO 중 한 개
		
		
		
		// 3. View 선택
		
		return null;
	}

}

 

Board(entity)

package kr.smhrd.entity;

public class Board {

	// 1. Table 컬럼명 == 필드 변수명
	private int num;
	private String title;
	private String writer;
	private String filename;
	private String content;
	
	// java.util.Date
	private String b_date;
	
	
	// 2. 기본생성자
	public Board () {
		
	}

	
	// 3. Getter / Setter
	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	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 getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getContent() {
		return content;
	}

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

	public String getB_date() {
		return b_date;
	}

	public void setB_date(String b_date) {
		this.b_date = b_date;
	}
	
}

 

BoardDAO

package kr.smhrd.dao;

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

public class BoardDAO {

	// 1. DB와 연결들 가져오기
	private SqlSessionFactory factory = 
			SqlSessionManager.getSqlSessionFactory();
	
	// 2. 기능 구현
	
	
}

 

BoardMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.smhrd.dao.BoardDAO">

</mapper>

 

mybatis-config.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>

	<properties resource="kr/smhrd/dao/db.properties"></properties>
	<!-- 위 properties는 db.properties와 연결되어 있다. -->

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <!-- 
      
      	(전)JDBC => 매번 실행할때마다 Connection 생성
      	
      	(후)Connection Pool -> Connection 미리 여러 개 만들어서 필요할 때 빌려만 주자.
      	Connection Pool을 만들기 위해 필요한 4가지 정보를 입력해라.
      
       -->
      
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  
  
  <!-- 우리 sql문은 어디에 있는가? -->
  <mappers>
    <mapper resource="kr/smhrd/dao/MemberMapper.xml"/>
    <mapper resource="kr/smhrd/dao/BoardMapper.xml"/>
  </mappers>
</configuration>

 


최종

BoardMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.smhrd.dao.BoardDAO">

<!-- 게시글 작성 저장 -->
<insert id="write" parameterType="kr.smhrd.entity.Board">
	insert into web_board
	values(	num_board.nextval, 
			#{title}, 
			#{writer}, 
			#{filename}, 
			#{content}, 
			sysdate
			)
</insert>

<select id="selectB" resultType="kr.smhrd.entity.Board">
	select * from web_board
</select>


</mapper>

 

BoardDAO

package kr.smhrd.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import kr.smhrd.entity.Board;

public class BoardDAO {

	// 1. DB와 연결들 가져오기
	private SqlSessionFactory factory = 
			SqlSessionManager.getSqlSessionFactory();
	
	// 2. 기능 구현
	public int write(Board dto) {
		SqlSession session = factory.openSession(true);
		int row = session.insert("write", dto);
		session.close();
		return row;
	}
	
	// 게시글 조회 기능
	public List<Board> select() {
		SqlSession session = factory.openSession(true);
		List<Board> user = session.selectList("selectB");
		session.close();
		return user;
	}
}

 

mybatis-config.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>

	<properties resource="kr/smhrd/dao/db.properties"></properties>
	<!-- 위 properties는 db.properties와 연결되어 있다. -->

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <!-- 
      
      	(전)JDBC => 매번 실행할때마다 Connection 생성
      	
      	(후)Connection Pool -> Connection 미리 여러 개 만들어서 필요할 때 빌려만 주자.
      	Connection Pool을 만들기 위해 필요한 4가지 정보를 입력해라.
      
       -->
      
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  
  
  <!-- 우리 sql문은 어디에 있는가? -->
  <mappers>
    <mapper resource="kr/smhrd/dao/MemberMapper.xml"/>
    <mapper resource="kr/smhrd/dao/BoardMapper.xml"/>
  </mappers>
</configuration>

 

writerBoard.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
		<title>Forty by HTML5 UP</title>
		<meta charset="UTF-8" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
		<link rel="stylesheet" href="assetsBoard/css/main.css" />
		<link rel="stylesheet" href="assetsBoard/css/board.css" />
		<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
		<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
</head>
<body>

			<div id = "board">
				<!-- 
					enctype : 기본값 => application/x-www-form-urlencoded
								    => Key값과 Value 형태로 데이터 전송
							: 파일 업로드 시 => multipart/form-date 
										  => 이미지 등과 같은 용량이 큰 데이터 전송
				 -->
				<form action="writeBoard.do" method="post" enctype="multipart/form-data">
				<table id="list">
					<tr>
						<td>제목</td>
						<td><input type="text" name="title"> </td>
					</tr>
					<tr>
						<td>작성자</td>
						<td><input  type="text" name="writer"> </td>
					</tr>
					<tr>
						<td colspan="2">내용</td>
					</tr>
					<tr>
						<td colspan="2">
							<input  type="file" style="float: right;" name="filename">
							<textarea  rows="10" style="resize: none;" name="content"></textarea>			
						</td>
					</tr>
					<tr>
						<td colspan="2">
							<input type="reset" value="초기화">
							<input type="submit" value="작성하기">
						</td>
					</tr>
				</table>
				</form>
			</div>
			<!-- Scripts -->
			<script src="assets/js/jquery.min.js"></script>
			<script src="assets/js/jquery.scrolly.min.js"></script>
			<script src="assets/js/jquery.scrollex.min.js"></script>
			<script src="assets/js/skel.min.js"></script>
			<script src="assets/js/util.js"></script>
			<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
			<script src="assets/js/main.js"></script>
</body>
</html>

 

WriteBoardController

package kr.smhrd.controller;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import kr.smhrd.dao.BoardDAO;
import kr.smhrd.entity.Board;

public class WriteBoardController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 1) 데이터 수집
		// post방식 인코딩
		request.setCharacterEncoding("UTF-8");
		
		// 1. 모든 요청 정보가 들어있는 request 객체
		// 2. 업로드 된 파일(이미지)을 저장할 경로(DB에 이미지를 저장X, 경로만 저장O)
		// "C:/users/..." 해당 경로는 에러가 날 확률이 높음
		// ∵ Linux는 "home/~", Window "C:/~"로 경로가 저장되기 때문에 
		//	 아래와 같은 코드를 사용
		String path = request.getServletContext().getRealPath("file");
		
		System.out.println(path);
		
		// 3. 파일의 max size (단위 : byte)
		int maxSize = 10*1024*1024; // 10MB(1MB=1024byte)
		
		// 4. 인코딩 방식
		String encoding = "UTF-8";
		
		// 5. 파일이름 중복제거 => 파일명 뒤에 숫자를 붙여주는 객체
		DefaultFileRenamePolicy rename = new DefaultFileRenamePolicy();
		
		// 파일 업로드 => MultipartRequest
		// 필요한 라이브러리 => cos.jar
		MultipartRequest multi = new MultipartRequest(request, path, maxSize, encoding, rename);
		
		// DB에 저장하기 위해서 게시글 정보 가져오기
		String title = multi.getParameter("title");
		String writer = multi.getParameter("writer");
		String content = multi.getParameter("content");
		
		// 우리가 파일의 이름을 가져올 때 save
		String filename = multi.getFilesystemName("filename");
		
//		System.out.println(title);
//		System.out.println(writer);
//		System.out.println(filename);
//		System.out.println(content);
		
		Board dto = new Board();
		dto.setTitle(title);
		dto.setWriter(writer);
		dto.setFilename(filename);
		dto.setContent(content);
		
		
		// 2) 기능 구현
		// 게시글 작성 => web_board 테이블에 게시글 데이터를 저장하겠다.
		// 1. DTO/VO 중 한 개
		// 2. 테이블 별 DAO / Mapper
		BoardDAO dao = new BoardDAO();
		int row= dao.write(dto);
		
		// 3. View 선택
		// 게시글 목록을 보여주기
		HttpSession session = request.getSession();
		session.setAttribute("row", row);
		
		return "redirect:/goBoardMain.do";
	}

}

 

게시글 조회

GoBoardMainCon

package kr.smhrd.controller;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.smhrd.dao.BoardDAO;
import kr.smhrd.entity.Board;

public class GoBoardMainCon implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		BoardDAO dao = new BoardDAO();
		List<Board> list = dao.select();
		
		request.setAttribute("list", list);
		
		return "boardMain";
	}

}

 

boardMain.jsp

<%@page import="kr.smhrd.entity.Board"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
		<title>Forty by HTML5 UP</title>
		<meta charset="utf-8" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
		<link rel="stylesheet" href="assetsBoard/css/main.css" />
		<link rel="stylesheet" href="assetsBoard/css/board.css" />
		<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
		<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
		
</head>
<body>		
		<% List<Board> list = (List<Board>)request.getAttribute("list"); %>
			<div id="board">
				<table id = "list">
					<tr>
						<td>번호</td>
						<td>제목</td>
						<td>작성자</td>
						<td>시간</td>
					</tr>
					<%for(Board dto :list){%>
					<tr>
						<td><%=dto.getNum() %></td>
						<td><%=dto.getTitle() %></td>
						<td><%=dto.getWriter() %></td>
						<td><%=dto.getB_date() %></td>
					</tr>
					<%} %>
				
				</table>
				
				<a href="goBoardMain.do"><button id="writer">홈으로가기</button></a>
				<a href="goWriterBoard.do"><button id="writer">작성하러가기</button></a>
			</div>


			<!-- Scripts -->
			<script src="assets/js/jquery.min.js"></script>
			<script src="assets/js/jquery.scrolly.min.js"></script>
			<script src="assets/js/jquery.scrollex.min.js"></script>
			<script src="assets/js/skel.min.js"></script>
			<script src="assets/js/util.js"></script>
			<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
			<script src="assets/js/main.js"></script>
</body>
</html>

 


 

위 FrontController는 if / else if 문을 작성하였지만

Hashmap<K, V>로 FrontController를 변경

package kr.smhrd.frontController;

import java.io.IOException;
import java.util.HashMap;

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 javax.servlet.http.HttpSession;

import kr.smhrd.controller.Controller;
import kr.smhrd.controller.DeleteController;
import kr.smhrd.controller.GoBoardMainCon;
import kr.smhrd.controller.GoMainCon;
import kr.smhrd.controller.GoSelectController;
import kr.smhrd.controller.GoSuccessCon;
import kr.smhrd.controller.GoUpdateController;
import kr.smhrd.controller.GoWriterBoardCon;
import kr.smhrd.controller.JoinCon;
import kr.smhrd.controller.LoginCon;
import kr.smhrd.controller.LogoutController;
import kr.smhrd.controller.UpdateController;
import kr.smhrd.controller.WriteBoardController;
import kr.smhrd.dao.MemberDAO;
import kr.smhrd.entity.Member;

// 모든 요청을 받을 수 있도록 url-mapping을 *로 지정
// @WebServlet("*.do") => .do로 끝나는 모든 요청
@WebServlet("*.do")
public class FrontController extends HttpServlet {
	
	private HashMap<String, Controller> mappings;
	
	@Override
	public void init() throws ServletException {
		// Servlet이 메모리에 할당 됐을 때, 
		// 단 1번 실행
		// Servlet에서 필요한 변수를 세팅, 내부 값 초기화
		
		// URL-Mapping <=> POJO
		// HashMap 자료구조 (python dict)
		// => key : value 구조
		// URL-Mapping : POJO
		
		mappings = new HashMap<String, Controller>();
		
		// hashmap에 데이터 집어넣기
		// 새로운 기능이 생기면 put으로 추가만 해주자.
		mappings.put("/goMain.do", new GoMainCon());
		mappings.put("/goSuccess.do", new GoSuccessCon());
		mappings.put("/join.do", new JoinCon());
		mappings.put("/login.do", new LoginCon());
		mappings.put("/logout.do", new LogoutController());
		mappings.put("/update.do", new UpdateController());
		mappings.put("/goSelect.do", new GoSelectController());
		mappings.put("/goUpdate.do", new GoUpdateController());
		mappings.put("/delete.do", new DeleteController());
		mappings.put("/goBoardMain.do", new GoBoardMainCon());
		mappings.put("/goWriterBoard.do", new GoWriterBoardCon());
		mappings.put("/writeBoard.do", new WriteBoardController());
		
	}
	
	
	
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// url은 아래 주소 전체를 나타냄
		// http://localhost:8081/MessageSystem/join?email=1234
		
		// 1. 요청 구분
		// uri는 /MessageSystem/join 를 나타냄
		String uri = request.getRequestURI();
		
		// /MessageSystem 를 꺼내오는 방법
		String cpath = request.getContextPath();
		
		// /join만 떼오기
		// String.subString(); => 문자열 슬라이싱
		// ex) 안녕하세요.
		// ex) String.subString(2); => "하세요."
		// ex) String.subString(2, 3); => "하"
		String command = uri.substring(cpath.length());
		
		System.out.println(command);
		
		
		// ==========================================================
		
		Controller con = null; // 업캐스팅을 이용한 중복제거
		
		// 2. 요청에 따라서 기능을 실행
		// 각각의 url mapping에 따라서 알맞는 POJO(class)를 찾아오기
		// 자바의 자료구조
		String nextView = null;
		
		con = mappings.get(command);
		
		
		// ================================================================
		
		if(con != null) {
			
			nextView = con.execute(request, response);
			
		}
		
		// 3. 페이지 이동
		// 예외처리용
		if(nextView != null) {
			// redirect vs forward 구분하기 위해서 규칙필요
			// 앞으로 redirect 요청은 반드시 앞에 redirect:/를 붙이자.
			// goMain.do => redirect:/goMain.do
			if(nextView.contains("redirect:/")) {
				// nextView = "redirect:/goMain.do"
				// nextView.split(":/"); => ["redirect", "goMain.do"]
				response.sendRedirect(nextView.split(":/")[1]);	
			}else {
				RequestDispatcher rd = 
						request.getRequestDispatcher("WEB-INF/views/"+nextView+".jsp");
				rd.forward(request, response);
			}
		}
			
		
	}

}

 

for문을 쓴 boardMain.jsp 파일을

JSTL로 표현

<%@page import="kr.smhrd.entity.Board"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
		<title>Forty by HTML5 UP</title>
		<meta charset="utf-8" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
		<link rel="stylesheet" href="assetsBoard/css/main.css" />
		<link rel="stylesheet" href="assetsBoard/css/board.css" />
		<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
		<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
		
</head>
<body>		
		<%--
			1. EL
			2. JSTL
		 --%>
		<%  List<Board> list = (List<Board>)request.getAttribute("list");
			request.setAttribute("list", list);
		%>
			
			<div id="board">
				<table id = "list">
					<tr>
						<td>번호</td>
						<td>제목</td>
						<td>작성자</td>
						<td>시간</td>
					</tr>
					
					<c:forEach items="${list}" var="list">
					<tr>
							<td>${list.num}</td>
							<td>${list.title}</td>
							<td>${list.writer}</td>
							<td>${list.b_date}</td>
					</tr>
					</c:forEach>
					
				
				</table>
				
				<a href="goBoardMain.do"><button id="writer">홈으로가기</button></a>
				<a href="goWriterBoard.do"><button id="writer">작성하러가기</button></a>
			</div>


			<!-- Scripts -->
			<script src="assets/js/jquery.min.js"></script>
			<script src="assets/js/jquery.scrolly.min.js"></script>
			<script src="assets/js/jquery.scrollex.min.js"></script>
			<script src="assets/js/skel.min.js"></script>
			<script src="assets/js/util.js"></script>
			<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
			<script src="assets/js/main.js"></script>
</body>
</html>

'Web > JSP_Servlet' 카테고리의 다른 글

Ajax_이메일 중복 확인  (0) 2023.05.09
EL과 JSTL  (1) 2023.05.04
MVC_FrontController  (1) 2023.05.03
MVC_회원관리 시스템  (1) 2023.04.28
MVC_개인정보수정  (0) 2023.04.26

댓글