보라코딩

Day75_230413_ JSP, MyBatis 게시판, MVC 패턴 본문

코딩/Servlet, JSP, MyBatis

Day75_230413_ JSP, MyBatis 게시판, MVC 패턴

new 보라 2023. 4. 13. 18:03

view.jsp (상세페이지)

에서 selectOne으로 가져온 bvo를 session에 넣어두고

삭제 수정 업데이트 할때 쓰면 편리하다 :)

 


modify_ok.jsp

 

암호 불일치시 request에 bvo를 넣는다.

그럼 다시 수정페이지로 갔을때 기존에 입력했던 내용이 사라지지 않는다.

 

scope를 이용한 것인데

원래 session에 bvo를 넣어서 사용했었는데

수정 시 비밀번호 틀렸을 때는 request에 있는 bvo를 찾아온다!

 

 

 

 

 

위에는 request scope에 있는 데이터 (page scope부터 찾기 시작하기 때문)

아래는 session scope에 있는 데이터

 

 

 request scope에 넣었기 때문에 한번 응답하고 사라짐!!! (용도에 딱 알맞음)

 

 


modify_ok.jsp에서

암호불일치시

request.setAttribute("pass_check", "fail");

도 추가해주면

 

 

modify.jsp에서

script 안에 아래와 같이 코드 써줄 수 있다!

let pass_check = "${pass_check}";
if(pass_check == "fail"){
alert("암호불일치!!");
}

 


삭제 시에

댓글이 남아있는데 게시글만 삭제하고 싶으면

mapper와 dao에

댓글삭제 후 게시글삭제가 가능하게 해줘야한다!

 

 


forward 이렇게 사용가능

넘겨줘서 받아서 script에서 처리하든..

 

 


button으로 하면 onclick해서 script에 submit()해줘야 전달되고

처음부터 submit으로 만들면 바로 전달됨

 


 

11_BBS 최종.zip
6.56MB

 

 

 

 

 


MVC 패턴(모델2 방식)

 

 

 

 

 

 

 

 

 

1. 라이브러리에 필요한 jar 파일 갖다놓기

2. src에 패키지 생성하고 필요 파일 갖다놓은 후 정보변경

3. src내 필요한 패키지와 vo, dao 클래스 만든다

4. 시작페이지 만듬

 

5. src에 servlet 만듬

 

 

 

 

 

 

 

 

 

package com.mystudy.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/list")
public class ListController extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(">> ListController.doGet() 실행");
response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(">> ListController.doPost() 실행");
doGet(request, response);
}

}

 

 

이후 index.jsp 모델 1방식에서 2방식으로 변경

 

 

 

 


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>시간(main)</title>
<script>
function all_search(frm){
//alert(frm);
//location.href="list.jsp"; //모델1방식
//location.href="list"; //컨트롤러 요청방 처리(GET)
frm.action = "list"; //컨트롤러 요청
frm.submit();
}

function dept_search(frm){
frm.action = "dept"
frm.submit();
}
</script>
</head>
<body>
<h1>작업선택 [index.jsp]</h1>
<form method="post" name="testForm">
<!-- <button onclick="all_search(this.form)">전체보기</button> -->
<input type="button" value="전체보기" onclick="all_search(this.form)">
<input type="button" value="부서코드검색" onclick="dept_search(this.form)">
</form>

</body>
</html>

 

 

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>list.jsp</title>
<link rel="stylesheet" href="bootstrap-4.4.1-dist/css/bootstrap.css" >
</head>
<body>
<%-- ${list } --%>
<h2>전체목록 [list.jsp]</h2>
<table>
<tr class="table-warning">
<th>사번</th>
<th>성명</th>
<th>급여</th>
<th>직종</th>
<th>부서코드</th>
</tr>

<c:forEach var="vo" items="${list }">
<tr>
  <td class="table-light">${vo.employeeId}</td>
  <td class="table-primary">${vo.firstName}</td>
  <td class="table-secondary">${vo.salary}</td>
  <td class="table-success"> ${vo.job_id}</td>
  <td class="table-danger">${vo.department_id}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

 

listController.java

package com.mystudy.controller;

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

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 com.mystudy.model.dao.EmployeeDAO;
import com.mystudy.model.vo.EmployeeVO;

@WebServlet("/list")
public class ListController extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(">> ListController.doGet() 시작 ==========");

process(request, response);

System.out.println(">> ListController.doGet() 끝");
//response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(">> ListController.doPost() 시작 ==========");
//doGet(request, response);
process(request, response);
System.out.println(">> ListController.doPost() 끝");
}

private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(">>>> ListController.process() 시작 ==========");

// DB 데이터 조회 후 list.jsp페이지로 전달
//1. DB 연동작업
List<EmployeeVO> list = EmployeeDAO.getList();
System.out.println("list : "+ list);

//2. 응답페이지(list.jsp)에 전달(request 객체에 저장해서 전달)
//forwarding처리 scope상에 저장(page는 못써)
request.setAttribute("list", list);

//3. 페이지전환 - 응답할 페이지(list.jsp)로 포워딩
request.getRequestDispatcher("list.jsp").forward(request, response);

System.out.println(">>>> ListController.process() 끝");
}
}

 

 

 

 

 

 


즉 핵심은

 

view 화면에서 컨트롤러로 요청한다

(method="post" 핵심)

 

 

 

 

 

콘트롤러에서 post 방식으로 받아서

여기서 DB 작업시킨다

(mapper와 DAO 이용)

이후 scope에 넣어서 forward

 

 

 

 

forward 통해 넘어가면 jsp 화면으로 보내서

여기서 보여준다!

 

 

 


 

 

 

 

실습

<이름으로 검색>
- 화면이동
  index.jsp -> fullname.jsp -> fullnameList.jsp
  
- 요청처리 흐름
  index.jsp : fullname 요청

■ FullnameController(서블릿) : fullname.jsp 페이지로 이동
  fullname.jsp
    - 요청명 : fullnameList
    - 요청파라미터명 : fullname
- fullnameList 요청처리 서블릿 : FullnameListController

■ FullnameListController 서블릿 처리작업
1. 사용할 파라미터 값 추출
2. DAO.getFullnameList(fullname) 사용 데이터 조회
3. 조회된 데이터 request scope에 "list" 이름으로 저장
4. fullnameList.jsp 페이지로 위임처리

- mapper.xml select 태그 작성 처리
(입력된 문자열로 FIRST_NAME, LAST_NAME 2곳에서 찾기)
- fullnameList.jsp 작성해서 전달받은 데이터 화면출력




 

이름으로 검색

부서코드로 검색까지 

 

 

12_MVC_HR.zip
7.20MB