21.01.11 JSPCommunity 프로젝트(form, redirect 도입)

2021. 1. 11. 19:42JAVA/JSP Community 사이트 프로젝트

// doGet 메서드 호출
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doHandle(request, response);
	}

// doPost 메서드 호출
protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doHandle(request, response);
	}

// doGet, doPost 중 들어온 방식으로 처리
protected void doHandle(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		// 요청된 uri의 정보를 가져오기
		String requestURI = request.getRequestURI();
		// 가져온 uri의 정보를 /기준으로 쪼개기
		String[] requestUriBits = requestURI.split("/");

		// 만약, requestURIBits.length가 5보다 작으면
		// 즉, /jspCommunity/jsp/usr/article/list 와 같은 형식이 아니면 중지
		if (requestUriBits.length < 5) {
			response.getWriter().append("잘못된 요청입니다.");
			return;
		}

		String controllerName = requestUriBits[3];
		String actionMethodName = requestUriBits[4];
		String jspPath = null;

		// DB 서버 연결
		MysqlUtil.setDBInfo("127.0.0.1", "sbsst", "sbs123414", "jspCommunity");

		if (controllerName.equals("member")) {
			MemberController membercontroller = Container.membercontroller;

			if (actionMethodName.equals("list")) {
				jspPath = membercontroller.showList(request, response);
			}
		}

		if (controllerName.equals("article")) {
			ArticleController articleController = Container.articleController;

			if (actionMethodName.equals("list")) {
				jspPath = articleController.showList(request, response);
			}
			if (actionMethodName.equals("detail")) {
				jspPath = articleController.showDetail(request, response);
			}
			if (actionMethodName.equals("doWriteForm")) {
				jspPath = articleController.doWriteForm(request, response);
			}
			if (actionMethodName.equals("doWrite")) {
				jspPath = articleController.doWrite(request, response);
			}
			if (actionMethodName.equals("doModifyForm")) {
				jspPath = articleController.doModifyForm(request, response);
			}
			if (actionMethodName.equals("doModify")) {
				jspPath = articleController.doModify(request, response);
			}
			if (actionMethodName.equals("doDelete")) {
				jspPath = articleController.doDelete(request, response);
			}
		}

		// DB 서버 연결 종료
		MysqlUtil.closeConnection();

		request.getRequestDispatcher("/jsp/" + jspPath + ".jsp").forward(request, response);

	}

}

<articleController.java>

// 리스트 가져오기
public String showList(HttpServletRequest request, HttpServletResponse response) {

		int boardId = Integer.parseInt(request.getParameter("boardId"));

		List<Article> articles = articleService.getArticlesForPrintByBoardId(boardId);


		// 만약, 해당 게시판 번호의 게시판이 없으면 알림 메시지와 뒤로 돌아가기 실시
		if (articles.size() <= 0) {
			request.setAttribute("alertMsg", boardId + "번 게시물은 존재하지 않습니다. 게시판 번호를 확인하세요.");
			request.setAttribute("historyBack", true); // historyBack: 뒤로 돌아가기
			return "common/redirect";
		}

		request.setAttribute("articles", articles);

		return "usr/article/list";
	}



// 게시물 등록 폼
public String doWriteForm(HttpServletRequest request, HttpServletResponse response) {

		int boardId = Integer.parseInt(request.getParameter("boardId"));

		int memberId = Integer.parseInt(request.getParameter("memberId"));

		request.setAttribute("boardId", boardId);
		request.setAttribute("memberId", memberId);

		return "usr/article/doWriteForm";
	}
    
    
    
// 게시물 수정 폼
public String doModifyForm(HttpServletRequest request, HttpServletResponse response) {

		int id = Integer.parseInt(request.getParameter("id"));

		int boardId = Integer.parseInt(request.getParameter("boardId"));

		int memberId = Integer.parseInt(request.getParameter("memberId"));

		request.setAttribute("id", id);
		request.setAttribute("boardId", boardId);
		request.setAttribute("memberId", memberId);

		return "usr/article/doModifyForm";
	}

<doWriteForm.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.Map"%>
<%@ page import="java.util.List"%>
<%@ page import="com.sbs.example.jspCommunity.dto.Article"%>

<%
int boardId= (int) request.getAttribute("boardId");
int memberId= (int) request.getAttribute("memberId");
%>

<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>게시물 생성</title>
</head>
<body>
<h1>신규 게시물 등록</h1>
	
<form action="/jspCommunity/usr/article/doWrite" method="POST">
  <input type="hidden" name="boardId" value="<%= boardId %>">
  <input type="hidden" name="memberId" value="<%= memberId %>">
  <span>TITLE</span>
  <br/>
  <input type="text" name="title" maxlength="10" placeholder="제목 입력">
  <hr/>
  <span>BODY</span>
  <br/>
  <textarea type="text" name="body"  maxlength="1000" placeholder="내용 입력"></textarea>
  <hr/>
  <input type="submit" value="등록">
</form>
	
</body>
</html>

<doModifyForm.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.Map"%>
<%@ page import="java.util.List"%>
<%@ page import="com.sbs.example.jspCommunity.dto.Article"%>
<%
int id= (int) request.getAttribute("id");
int boardId= (int) request.getAttribute("boardId");
int memberId= (int) request.getAttribute("memberId");
%>
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>게시물 수정</title>
</head>
<body>
	<h1><%=id + "번"%> 게시물 수정</h1>
	<form action="/jspCommunity/usr/article/doModify" method="POST">
  <input type="hidden" name="id" value="<%= id %>">
  <input type="hidden" name="boardId" value="<%= boardId %>">
  <input type="hidden" name="memberId" value="<%= memberId %>">
  <span>TITLE</span>
  <br>
  <input type="text" name="title" maxlength="10" placeholder="수정할 제목 입력">
  <hr>
  <span>BODY</span>
  <br>
  <textarea type="text" name="body"  maxlength="1000" placeholder="수정할 내용 입력"></textarea>
  <hr>
  <input type="submit" value="수정 완료">
</form>
	
	
</body>
</html>

<redirect.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<script>
var alertMsg = '<%=request.getAttribute("alertMsg") %>'.trim();

if(alertMsg){
	alert(alertMsg);
}

var historyBack = '<%=request.getAttribute("historyBack") %>' == 'true';

if(historyBack){
	// history.go(-3);  => 뒤로가기 3회라는 의미
	// history.go(-1); == history.back();
	history.back();
}

var replaceUrl = '<%=request.getAttribute("replaceUrl") %>'.trim();

if(replaceUrl){
	// historyBack으로 뒤로 돌아갈 경로를 설정하는 것
	// location.replace()를 하지 않으면 그냥 뒤로가기가 되어 흔적이 남게 됨
	// location.replace()는 흔적이 남지 않고 설정된 replaceUrl로 historyBack 시행
	location.replace(replaceUrl);  
}
</script>

 

<결과>