Pojo - step1

지환·2023년 12월 5일
0

Jsp & Servlet

목록 보기
11/21
post-thumbnail

Action(interface)

package com.example.demo.pojo1;

import java.io.IOException;

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


public interface Action {
	public ActionForward execute(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException;
}

ActionForward.java

package com.example.demo.pojo1;

public class ActionForward {
	 private String path = null;
	 private boolean isRedirect = false;
	
	 
	 public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public boolean isRedirect() {
		return isRedirect;
	}
	public void setRedirect(boolean isRedirect) {
		this.isRedirect = isRedirect;
	}
	 
	 
}

FrontController

package com.example.demo.pojo1;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("*.fc")
public class FrontController extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
	}
	

	

}

FrontMVC

package com.example.demo.pojo1;

import java.io.IOException;

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

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 *  * **********@Insert : @int (입력)***********
 * http://localhost:8000/member/memberInsert.gd
 * http://localhost:8000/lecture/lectureInsert.gd
 * http://localhost:8000/notice/noticeInsert.gd
 * 
 * 
 *  * ******@Update : @int ***********
 * http://localhost:8000/member/memberUpdate.gd
 * http://localhost:8000/lecture/lectureUpdate.gd
 * http://localhost:8000/notice/noticeUpdate.gd
 * 
 * 
 * *******@Delete : @int ***********
 * http://localhost:8000/member/memberDelete.gd
 * http://localhost:8000/lecture/lectureDelete.gd
 * http://localhost:8000/notice/noticeDelete.gd
 * 
 * ==============================
 * select(dispatcher(forward)) - false 
 * select - forward - false
 * ********@Select : List<Map> - dispatcher ********** 
 *
 * http://localhost:8000/member/memberSelect.gd
 * http://localhost:8000/lecture/lectureSelect.gd
 * http://localhost:8000/notice/noticeSelect.gd
 * 
 * 
 */

//앞에 뭐가 오든지간에 접이머가 .gd로 끝나면 내가 간섭할게 라고 해석
@WebServlet("*.gd")
public class FrontMVC extends HttpServlet{
	/**
	 * ㅇㅇ
	 */
	private static final long serialVersionUID = 1L;
	Logger logger = LoggerFactory.getLogger(FrontMVC.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doService(req,res);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doService(req,res);
	}

	
	protected void doService(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		//http://localhost:8000/notice/noticeInsert.gd
		String uri = req.getRequestURI(); // >> /notice/noticeInsert.gd
		// ===>>> /notice/noticeInsert.gd (도메인 짤라서 옴)
		//만약에 이렇게 쓴다면, 배열로 만들 떄 문제가 발생한다.(.gd) 도 포함 그래서 제거해야된다.
		logger.info(uri);
		String context = req.getContextPath(); //===>>> /x   notice/
		// /notice/
		String command = uri.substring(context.length()+1); 
		// notice+1(/) 제외한 앞부터 start == noticeInsert.gd란 얘기(substring) 결과값
		// >>> notice/noticeInsert.gd 이렇게 나온다 (/)를 없애기 위해 +1 한 것.
		// 이제, gd를 제거해야된다.
		
		int end = command.lastIndexOf(".");
		// .에 대한 인덱스를 가져와서 noticeInsert.gd
		// 점이 있는 위치 정보를 가져온다.(lastIndexOf)가 들어간다.
		// command은 uri를 substring했기 떄문에 
		// noticeInsert.gd이기 떄문에 (.) 기준으로 인덱스를 구하면
		//command 재정의한다.
		command = command.substring(0,end); //   notice/noticeinsert까지만 가져온다 .gd는 제거한다.
		String upmu[] = null;
		upmu = command.split("/"); 
		//메소드 이름으로 들어간다. (/) 기준으로 나눈다.
		NoticeController nc = new NoticeController();
		//MemberController mc= new MemberController();
		//LectureController lc = new LectureController();
		
		ActionForward af = null;
		
		for(String name : upmu)
		{
			logger.info(name);
		}
		///이 지점은 내려가는 방향이다.
		if("notice".equals(upmu[0])) {
			req.setAttribute("upmu",upmu); // 배열을 보낸다.
			af = nc.execute(req, res);//NoticeController클래스로 건너감 - upmu[1]-메소드이름이니까...
		}// 3번에 위치하는 부분
		
		//이 지점은 java와 오라클 서버를 경유한 뒤 시점이다.
		if(af !=null) {
			if(af.isRedirect()) {
				res.sendRedirect(af.getPath());
			}
			else{
				RequestDispatcher view = req.getRequestDispatcher(af.getPath());
				view.forward(req, res);
			}
		}/////////// end of if - 응답페이지 호출하기 - 포워드
		else if("member".equals(upmu[0])) {
			
		}
		else if("lecture".equals(upmu[0])) {
			
		}
	
	
	}}


////////////////////[[ 어떤 컨트롤러를 태울 것인가?]]//////////////////////



////////////////////[[ 컨트롤을 타고 난 뒤에 내가 할일은?]]//////////////////////
// 해당 업무에 대응하는 컨트롤러에서 결정된 페이지 이름을 받아온다.
// 위에서 결정된 true 혹은 false 값에 따라 sendRedirect() 와 forward를 통해
// 응답 페이지를 호출해준다. -  FrontMVC의 역할이다.




NoticeController


package com.example.demo.pojo1;

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

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

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



public class NoticeController implements Action {
	Logger logger = LoggerFactory.getLogger(NoticeController.class);
	NoticeLogic nLogic = new NoticeLogic();//이른
	@Override
	public ActionForward execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String upmu[] = (String[])req.getAttribute("upmu"); 
		// 여기서 setAttribute를 받는다.
		// 이 부분에서 하나 얻을 수 있는 부분은 java와 서블릿간 대화를 할 때도 setAttribute를 진행한다.
		if("noticeList".equals(upmu[1])) {//select
			logger.info("noticeList");
			List<Map<String ,Object>> nList = null;
		}
		else if("noticeInsert".equals(upmu[1])) {//insert (여기서 디비와 비벼지는 부분이다)
			logger.info("noticeInsert");
			int result = 0;
			
		}else if("noticeUpdate".equals(upmu[1])) {//update
			logger.info("noticeUpdate");
			int result = 0;
			
		}else if("noticeDelete".equals(upmu[1])) {//delete
			logger.info("noticeDelete");
			int result = 0;
			
		}
		return null;
	}

}


//NoticeController는 서블릿을 상속받지 않았다 (결합도를 낮추고 싶어서) - 프레임워크 사상중에 하나이니깐 
//서블릿이 아닌데 req와 res는 어디서 주입받죠? -> doGet(req,res)는 톰캣이 주입해주기 때문에 NullPointException이 발생하지만
// 여기선 NullPointException이 발생한다.
// res,req를 설정해줘야되기 때문에 (주입) 새로 서블릿 파일을 만들어야한다.(FrontMVC)
// 이 말은 FrontMVC로부터 값을 주입받는다. 단, 톰캣이 아니기 떄문에 NullPointException이 발생할 수 있다.

NoticeLogic

package com.example.demo.pojo1;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

public class NoticeLogic {
	Logger logger = LoggerFactory.getLogger(NoticeLogic.class);
	
	public List<Map<String,Object>> noticeList()
	{
		logger.info("noticeList");
		List<Map<String,Object>> nList =  new ArrayList<>();
		return nList;
	}
	
	public int noticeInsert() //.gd
	{
		//리턴타입 int
		int result = 0;
		return result;
	}
	
	public int noticeUpdate() //.gd
	{
		//리턴타입 int
		int result = 0;
		return result;
	}
	
	public int noticeDelete() //.gd
	{
		//리턴타입 int
		int result = 0;
		return result;
	}
	
	
}

NoticeLogic

package com.example.demo.pojo1;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

public class NoticeLogic {
	Logger logger = LoggerFactory.getLogger(NoticeLogic.class);
	
	public List<Map<String,Object>> noticeList() // select
	{
		logger.info("noticeList");
		List<Map<String,Object>> nList =  new ArrayList<>();
		return nList;
	}
	
	public int noticeInsert() // Insert
	{
		//리턴타입 int
		int result = 0;
		return result;
	}
	
	public int noticeUpdate() //Update
	{
		//리턴타입 int
		int result = 0;
		return result;
	}
	
	public int noticeDelete() //delete
	{
		//리턴타입 int
		int result = 0;
		return result;
	}
	
	
}

큰 틀

  1. xxx(*).gd에 대한 처리는 : 업무이름/메소드로 설계 예정이다. -> 배열로 저장한 다음 Tokenizer / Splice를 이용해서 자른다.

  2. FrontMVC를 반드시 경유해야하며, 기존에는 HttpServlet를 상속받아서 사용했지만, 이렇게 하지 않고 사용자정의함수로 doService 메소드를 사용해서 doGet() / doPost 처리를 할 것이다.

  1. FrontMVC로부터 배열로 전달을 받으며,

    1. 컨트롤 계층은 4개의 메소드를 반드시 갖는다.

      1. 컨트롤(SELECT) <-> 자바(SELECT)
      2. 컨트롤(DELETE) <-> 자바(DELETE)
      3. 컨트롤(UPDATE) <-> 자바(UPDATE)
      4. 컨트롤(INSERT) <-> 자바(INSERT)
    2. 컨트롤 계층도 MemberController, NoticeController, LectureController가 존재한다. 이 컨트롤러에는 4가지 메소드가 존재하는 것이다.

    3. 그리고 Action 인터페이스를 상속받으며, execute라는 메소드를 @Overide한다. 왜 가운데 Action이라는 인터페이스를 두고 구현했을까? -> 결합도를 낮추기 위해서다.

      • 그리고 ActionForward 사용하는 이유는 해당 클래스는 불변객체이며, url에 대한 처리 및 리다이렉트포워드 설정을 한다. 이 부분은 중요한 부분이므로 꼭 알고 있어야한다.
    4. 컨트롤러 계층은 모델계층과 유기적인 관계를 갖는다. 모델, 즉, 처리 계층은 순수한 자바로 되어 있으며 디비와 소통한다.

    5. 그렇다면 각각의 컨트롤계층은 HttpServlet를 상속받지 않았는데, 어떻게 사용 가능하지?

      • FrontMVC에서 HttpServlet를 상속받으며, 여기서 url에대한 슬라이싱을 진행하고, 배열에 저장한 다음

      • 이걸 기준으로 if문으로 분기 후(execute 실행 및 req,res)객체주입한다. 그 후에 디비 및 자바코드의 결과값을 받아온 다음 ActionForward를 통해서 경로설정한다.

        • 특이사항은 req,res는 기존에 톰캣에서 관리해줬기 때문에 NullPointException이 발생하지 않았지만, 지금부터는 NullPointException이 발생한다.

소스리뷰

Action(interface)

package com.example.demo.pojo1;

import java.io.IOException;

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


public interface Action {
	public ActionForward execute(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException;
}
  • 반환타입이 ActionForward라는 점을 숙지하고 있어야한다.

ActionForward.java

package com.example.demo.pojo1;

public class ActionForward {
	 private String path = null;
	 private boolean isRedirect = false;
	
	 
	 public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public boolean isRedirect() {
		return isRedirect;
	}
	public void setRedirect(boolean isRedirect) {
		this.isRedirect = isRedirect;
	}
	 
	 
}
  • path : 설정을 String으로 한 이유
  • isRedirect: 를 false로 지정한 이유는
    • true : sendRedirect
    • false : foward 이다.

FrontMVC

package com.example.demo.pojo1;

import java.io.IOException;

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

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 *  * **********@Insert : @int (입력)***********
 * http://localhost:8000/member/memberInsert.gd
 * http://localhost:8000/lecture/lectureInsert.gd
 * http://localhost:8000/notice/noticeInsert.gd
 * 
 * 
 *  * ******@Update : @int ***********
 * http://localhost:8000/member/memberUpdate.gd
 * http://localhost:8000/lecture/lectureUpdate.gd
 * http://localhost:8000/notice/noticeUpdate.gd
 * 
 * 
 * *******@Delete : @int ***********
 * http://localhost:8000/member/memberDelete.gd
 * http://localhost:8000/lecture/lectureDelete.gd
 * http://localhost:8000/notice/noticeDelete.gd
 * 
 * ==============================
 * select(dispatcher(forward)) - false 
 * select - forward - false
 * ********@Select : List<Map> - dispatcher ********** 
 *
 * http://localhost:8000/member/memberSelect.gd
 * http://localhost:8000/lecture/lectureSelect.gd
 * http://localhost:8000/notice/noticeSelect.gd
 * 
 * 
 */

//앞에 뭐가 오든지간에 접이머가 .gd로 끝나면 내가 간섭할게 라고 해석
@WebServlet("*.gd")
public class FrontMVC extends HttpServlet{
	/**
	 * ㅇㅇ
	 */
	private static final long serialVersionUID = 1L;
	Logger logger = LoggerFactory.getLogger(FrontMVC.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doService(req,res);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doService(req,res);
	}

	
	protected void doService(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		//http://localhost:8000/notice/noticeInsert.gd
		String uri = req.getRequestURI(); // >> /notice/noticeInsert.gd
		// ===>>> /notice/noticeInsert.gd (도메인 짤라서 옴)
		//만약에 이렇게 쓴다면, 배열로 만들 떄 문제가 발생한다.(.gd) 도 포함 그래서 제거해야된다.
		logger.info(uri);
		String context = req.getContextPath(); //===>>> /x   notice/
		// /notice/
		String command = uri.substring(context.length()+1); 
		// notice+1(/) 제외한 앞부터 start == noticeInsert.gd란 얘기(substring) 결과값
		// >>> notice/noticeInsert.gd 이렇게 나온다 (/)를 없애기 위해 +1 한 것.
		// 이제, gd를 제거해야된다.
		
		int end = command.lastIndexOf(".");
		// .에 대한 인덱스를 가져와서 noticeInsert.gd
		// 점이 있는 위치 정보를 가져온다.(lastIndexOf)가 들어간다.
		// command은 uri를 substring했기 떄문에 
		// noticeInsert.gd이기 떄문에 (.) 기준으로 인덱스를 구하면
		//command 재정의한다.
		command = command.substring(0,end); //   notice/noticeinsert까지만 가져온다 .gd는 제거한다.
		String upmu[] = null;
		upmu = command.split("/"); 
		//메소드 이름으로 들어간다. (/) 기준으로 나눈다.
		NoticeController nc = new NoticeController();
		//MemberController mc= new MemberController();
		//LectureController lc = new LectureController();
		
		ActionForward af = null;
		
		for(String name : upmu)
		{
			logger.info(name);
		}
		///이 지점은 내려가는 방향이다.
		if("notice".equals(upmu[0])) {
			req.setAttribute("upmu",upmu); // 배열을 보낸다.
			af = nc.execute(req, res);//NoticeController클래스로 건너감 - upmu[1]-메소드이름이니까...
		}// 3번에 위치하는 부분
		
		//이 지점은 java와 오라클 서버를 경유한 뒤 시점이다.
		if(af !=null) {
			if(af.isRedirect()) {
				res.sendRedirect(af.getPath());
			}
			else{
				RequestDispatcher view = req.getRequestDispatcher(af.getPath());
				view.forward(req, res);
			}
		}/////////// end of if - 응답페이지 호출하기 - 포워드
		else if("member".equals(upmu[0])) {
			
		}
		else if("lecture".equals(upmu[0])) {
			
		}
	
	
	}}


////////////////////[[ 어떤 컨트롤러를 태울 것인가?]]//////////////////////



////////////////////[[ 컨트롤을 타고 난 뒤에 내가 할일은?]]//////////////////////
// 해당 업무에 대응하는 컨트롤러에서 결정된 페이지 이름을 받아온다.
// 위에서 결정된 true 혹은 false 값에 따라 sendRedirect() 와 forward를 통해
// 응답 페이지를 호출해준다. -  FrontMVC의 역할이다.



  1. @WebServlet(".gd") : 리고 작성한 부분에 대한 해석은 url에서 .gd로 끝나는건 내가 모두 가로챌게 라는 얘기다.

예시

 *  * **********@Insert : @int (입력)***********
 * http://localhost:8000/member/memberInsert.gd
 * http://localhost:8000/lecture/lectureInsert.gd
 * http://localhost:8000/notice/noticeInsert.gd
 * 
 * 
 *  * ******@Update : @int ***********
 * http://localhost:8000/member/memberUpdate.gd
 * http://localhost:8000/lecture/lectureUpdate.gd
 * http://localhost:8000/notice/noticeUpdate.gd
 * 
 * 
 * *******@Delete : @int ***********
 * http://localhost:8000/member/memberDelete.gd
 * http://localhost:8000/lecture/lectureDelete.gd
 * http://localhost:8000/notice/noticeDelete.gd
 * 
 * ==============================
 * select(dispatcher(forward)) - false 
 * select - forward - false
 * ********@Select : List<Map> - dispatcher ********** 
 *
 * http://localhost:8000/member/memberSelect.gd
 * http://localhost:8000/lecture/lectureSelect.gd
 * http://localhost:8000/notice/noticeSelect.gd
  1. 두 번쨰로 중요한 부분은 doService라는 사용자정의 메소드를 만들어서 doGet(req,res) + doPost(req,res)로 오든지간에 doService(req,res)로 호출한다.

    • 다음은 url을 배열로 바꾸는 작업이다.

      		//http://localhost:8000/notice/noticeInsert.gd
      		String uri = req.getRequestURI(); // >> /notice/noticeInsert.gd
      		// ===>>> /notice/noticeInsert.gd (도메인 짤라서 옴)
      		//만약에 이렇게 쓴다면, 배열로 만들 떄 문제가 발생한다.(.gd) 도 포함 그래서 제거해야된다.
      		logger.info(uri);
      		String context = req.getContextPath(); //===>>> /x   notice/
      		// /notice/
      		String command = uri.substring(context.length()+1); 
      		// notice+1(/) 제외한 앞부터 start == noticeInsert.gd란 얘기(substring) 결과값
      		// >>> notice/noticeInsert.gd 이렇게 나온다 (/)를 없애기 위해 +1 한 것.
      		// 이제, gd를 제거해야된다.
      	
      		int end = command.lastIndexOf(".");
      		// .에 대한 인덱스를 가져와서 noticeInsert.gd
      		// 점이 있는 위치 정보를 가져온다.(lastIndexOf)가 들어간다.
      		// command은 uri를 substring했기 떄문에 
      		// noticeInsert.gd이기 떄문에 (.) 기준으로 인덱스를 구하면
      		//command 재정의한다.
      		command = command.substring(0,end); //   notice/noticeinsert까지만 가져온다 .gd는 제거한다.
      		String upmu[] = null;
      		upmu = command.split("/"); 
      
    • 만약에 http://localhost:8000/notice/noticeInsert.gd 호출한다면,
      String uri = req.getRequestURI();를 통해서 도메인을 제외한 url를 가져오고. (/notice/noticeInsert.gd)

    • String context = req.getContextPath();를 통해서 ContextRoot를 가져온다. 여기선 (/notice/)이다.

    • String command = uri.substring(context.length()+1); 이렇게 하면 context.length()+1는 /notice/noticeInsert.gd 여기서 앞에 /를 제외하기 위해 +1를 했다.
      (결과값: notice/noticeInsert.gd)

    • 다음은 .gd를 지워주기 위해 lastIndexOf를 사용할 것이다.

      • lastIndexOf를 통해서 .의 인덱스를 구하고
      • command를 재정의하여 command.substring(0,end)까지 진행한다.(end)는 (.)의 인덱스
    • 그리고 배열로 어떻게 만들까? split("/") 이렇게 하면 배열타입으로 반환한다. 그럼 url기준 notice/noticeInsert 이니깐 0번방엔 notice | noticeInsert가 들어간다.

      • 더 중요한 부분은 notice는 컨트롤계층의 이름이고
      • noticeInsert는 메소드이다.(어디 메소드?) 순수자바(메소드)

로그를 찍었을 떄 결과가 이렇게 나온다.


(2/2)

		NoticeController nc = new NoticeController();
		//MemberController mc= new MemberController();
		//LectureController lc = new LectureController();
		
		ActionForward af = null;
		
		for(String name : upmu)
		{
			logger.info(name);
		}
		///이 지점은 내려가는 방향이다.
		if("notice".equals(upmu[0])) {
			req.setAttribute("upmu",upmu); // 배열을 보낸다.
			af = nc.execute(req, res);//NoticeController클래스로 건너감 - upmu[1]-메소드이름이니까...
		}// 3번에 위치하는 부분
		
		//이 지점은 java와 오라클 서버를 경유한 뒤 시점이다.
		if(af !=null) {
			if(af.isRedirect()) {
				res.sendRedirect(af.getPath());
			}
			else{
				RequestDispatcher view = req.getRequestDispatcher(af.getPath());
				view.forward(req, res);
			}
		}/////////// end of if - 응답페이지 호출하기 - 포워드
		else if("member".equals(upmu[0])) {
			
		}
		else if("lecture".equals(upmu[0])) {
			
		}
	
	
	}}
  • 여기서 notice는 0번방의 컨트롤 계층의 이름이다. 즉 이 부분에서 조건을 분기하는 것이다.

    • "notice".equals(upmu[0])랑 같으면
    • req.setAttribute("upmu",upmu); 배열 객체를 setAttribute로 담아서 보낸다. -> 이걸 noticeController에서 받는다.
    • 메소드 이름을 가지고 NoticeController에서 if문을 적어야한다.
      • noticeList
      • noticeInsert
      • noticeUpdate
      • noticeDelete
    • 설계 관점이 아쉽다.(xxxController) 에서부터 메소드를 가질 수 없었나?

    • af는 ActionForwrd를 선언한 이유는 무엇일까?

      • nc.execute의 리턴타입이 ActionForwrd이기 때문이다.
        (설계의 중요성)
      • nc.execute(req,res); 이 부분에서 req,res주입이 발생하고, NoticeController 클래스로 넘어가는 부분이다.
      • 그렇다면, NoticeController 에서 af의 경로와 디비의 정보를 받는다는점을 알 수 있다.
    • 이후에 if문을 통해서 af가 true이면 sendRedirect를 하고 af가 false이면 forward를 진행한다.

      • 이 때 시점의 문제를 봐야된다. af는 nc.execute의 결과값을 받고 이 결과를 기반으로 if문을 분기하여 처리한다.

아쉬운점

  1. xxxController에서부터 메소드를 가질 수는 없었나?

  2. 메소드마다 req,res에 대한 객체 주입을 처리할 수 없는 구조이다.

NoticeController

package com.example.demo.pojo1;

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

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

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



public class NoticeController implements Action {
	Logger logger = LoggerFactory.getLogger(NoticeController.class);
	NoticeLogic nLogic = new NoticeLogic();//이른
	@Override
	public ActionForward execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String upmu[] = (String[])req.getAttribute("upmu"); 
		// 여기서 setAttribute를 받는다.
		// 이 부분에서 하나 얻을 수 있는 부분은 java와 서블릿간 대화를 할 때도 setAttribute를 진행한다.
		if("noticeList".equals(upmu[1])) {//select
			logger.info("noticeList");
			List<Map<String ,Object>> nList = null;
		}
		else if("noticeInsert".equals(upmu[1])) {//insert (여기서 디비와 비벼지는 부분이다)
			logger.info("noticeInsert");
			int result = 0;
			
		}else if("noticeUpdate".equals(upmu[1])) {//update
			logger.info("noticeUpdate");
			int result = 0;
			
		}else if("noticeDelete".equals(upmu[1])) {//delete
			logger.info("noticeDelete");
			int result = 0;
			
		}
		return null;
	}

}
  • NoticeLogic nlogic = new NoticeLogic(); 으로 이른인스턴스화를 진행했다. 왜? NullPointException이 발생할 수 있어서

  • 우선 여기서 조건에 대한 분기를 진행한다. String upmu[] = (String[])req.getAttribute("upmu"); 이 부분을 살펴보면, upmu라는 배열을 받아서 String[] 배열 형태로 다시 저장하고 있다.

    • select

      		if("noticeList".equals(upmu[1])) {//select
      					logger.info("noticeList");
      					List<Map<String ,Object>> nList = null;
      				}
    • insert

      		else if("noticeInsert".equals(upmu[1])) {//insert (여기서 디비와 비벼지는 부분이다)
      					logger.info("noticeInsert");
      					int result = 0;
      			
      				}
    • update

      else if("noticeUpdate".equals(upmu[1])) {//update
      					logger.info("noticeUpdate");
      					int result = 0;
      			
      				}
    • delete

      else if("noticeDelete".equals(upmu[1])) {//delete
      					logger.info("noticeDelete");
      					int result = 0;
      			
      				}
  • result는 어디서 가져왔는가? NoticeLogic에서 return 값임

NoticeLogic

package com.example.demo.pojo1;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

public class NoticeLogic {
	Logger logger = LoggerFactory.getLogger(NoticeLogic.class);
	public List<Map<String,Object>> noticeList(){
		logger.info("noticeList");
		List<Map<String,Object>> nList = new ArrayList<>();
		return nList;
	}
	public int noticeInsert(){
		logger.info("noticeInsert");
		int result = 0;
		return result;
	}
	public int noticeUpdate(){
		logger.info("noticeUpdate");
		int result = 0;
		return result;
	}
	public int noticeDelete(){
		logger.info("noticeDelete");
		int result = 0;
		return result;
	}
}
  • noticeList, noticeInsert, noticeUpdate, noticeDelete 전부 배열[1] 값이다.

  • 이 부분이 디비와 비벼지는 부분이며, 추후에 SELECT문을 할 시 로직에서 nList를 하고 있다.

  • 모든 리턴값은 디비로부터 꺼낸 값을 성공했을떄 리턴값이며, 아직 연동하지 않았기 때문에 값을 알 수 없다.


정리

ActionForward의 활용 방법은 뭘까?

  • ActionForward의 인스턴스로 전변의 담긴 값을 사용할 수 있다. 컨트롤 계층을 타고 난 뒤

  • 처리를 담당하는 Java클래스를 경유하고 나서 반환값으로 받은 정보를 Jsp 페이지에 유지하거나 또는 페이지 처리를 해야한다.

전변 path에는 어떤 정보를 담을 생각인가?

  • 컨트롤 계층에서 돌려 받은 정보가 ActionForward이니깐 그 인스턴스로 getPath()메소드를 호출할 수 있고, path전변에 담긴 정보는 응답을 처리해줄 페이지 이름으로 사용될 것이다.

isRedirect는 왜 boolean으로 했나?

  • af가 null이 아니면 정상적으로 처리를 받아온 상태 일 테니깐 af.isRedirect()의 반환값에 따라서 sendRedirect 가 될지 forward가 될지 결정하는 용도로 사용된다.
profile
아는만큼보인다.

0개의 댓글