기록해! 정리해!

MVC 프레임워크 구현하기 본문

Spring

MVC 프레임워크 구현하기

zsuling 2022. 9. 23. 16:41

[ web.xml ]

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://Java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>com.springbook.view.mvc.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
</web-app>
=====================================================================

​

package com.springbook.view.mvc;

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

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

import com.springbook.biz.board.BoardDao;
import com.springbook.biz.board.BoardVo;
import com.springbook.biz.board.impl.BoardDaoImpl;
import com.springbook.biz.user.UserVo;
import com.springbook.biz.user.impl.UserDao3;
import com.springbook.view.controller.Controller;

/**
 * Servlet implementation class DispatcherServlet
 */
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private HandlerMapping handlerMapping;
	private ViewResolver viewResolver;

	public  void init() throws ServletException  {
		handlerMapping = new HandlerMapping();
		viewResolver = new ViewResolver();
		viewResolver.setPrefix("./");   // 접두사
		viewResolver.setSuffix(".jsp"); // 접미사		
	}
	

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		try {
			process(request,response );
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		try {
			process(request,response );
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void process(HttpServletRequest request, HttpServletResponse response)
 throws Exception {

      //request.setCharacterEncoding("UTF-8");
	  
      // 1. 클라이언트 요청  path정보를 추출한다.
	  String uri=request.getRequestURI();              // 결과 :  /BoardWeb/delete.do
	  String path=uri.substring(uri.lastIndexOf("/")); // 결과 :  /delete.do
	  System.out.println("경로확인:" +path);
	  
	  // 2. handlerMapping 을 통해  path에 해당되는 Controller을 검색한다.
	  Controller ctrl = handlerMapping.getController(path);
	  
	  // 3. 검색된 컨트롤의 handleRequest() 메소드 실행한다. 
	  String viewName = ctrl.handleRequest(request, response) ;
	  
	      // 4. viewResolver 를 통해 viewName에 해당되는 화면을 검색한다. 
	      String  view =null;
		  if(!viewName.contains(".do")) {
			  // .do 가 아니면 ./viewName.jsp 가 된다. 
			  view =  viewResolver.getView(viewName);  
		  }else {		
			  // viewName.do 가 된다.
			  view = viewName ;
		  }	
		  // 5. 검색된 화면으로 이동
		  response.sendRedirect(view);	
	}
}
=======================================================================

​

package com.springbook.view.mvc;

import java.util.HashMap;
import java.util.Map;

import com.springbook.view.controller.Controller;
import com.springbook.view.controller.DeleteBoardController;
import com.springbook.view.controller.GetBoardController;
import com.springbook.view.controller.GetBoardListController;
import com.springbook.view.controller.InsertBoardController;
import com.springbook.view.controller.LoginController;
import com.springbook.view.controller.LogoutController;
import com.springbook.view.controller.UpdateBoardController;

public class HandlerMapping {
  private  Map<String,  Controller> mappings; 
  
  public HandlerMapping(){
	  mappings =new HashMap<String,  Controller>();
	  mappings.put("/login.do", new LoginController());
	  mappings.put("/logout.do", new LogoutController());
	  mappings.put("/insertBoard.do", new InsertBoardController());
	  mappings.put("/updateBoard.do", new UpdateBoardController());
	  mappings.put("/deleteBoard.do", new DeleteBoardController());
	  mappings.put("/getBoard.do", new GetBoardController());
	  mappings.put("/getBoardList.do", new GetBoardListController());
  }
  
  public  Controller  getController(String  path) {
	  
	   return mappings.get(path);
	  
  }
}
======================================================================

​

package com.springbook.view.mvc;

public class ViewResolver {
   public  String  prefix; // 접두사  ./
   public  String  suffix; // 접미사  .jsp
   
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}
	   
   public  String  getView(String  viewName) {
	   
	   // 예) getBoard  ==>  ./getBoard.jsp
	   return prefix + viewName + suffix;
	   	   
   }
}

[ Controller ]

package com.springbook.view.controller;

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

public interface Controller {
  String handleRequest(HttpServletRequest request, HttpServletResponse response);
}
----------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

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

import com.springbook.biz.board.BoardDao;
import com.springbook.biz.board.impl.BoardDaoImpl;

public class DeleteBoardController implements  Controller {
	public DeleteBoardController(){
		System.out.println("===>DeleteBoardController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		   System.out.println("글 삭제 처리"); 

		   //request.setCharacterEncoding("UTF-8");
		   int seq= Integer.parseInt(request.getParameter("seq")) ;
		   BoardDao dao = new BoardDaoImpl();
		   dao.delete(seq);
		  
		return "getBoardList.do";
	}

}
------------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

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

import com.springbook.biz.board.BoardDao;
import com.springbook.biz.board.BoardVo;
import com.springbook.biz.board.impl.BoardDaoImpl;

public class GetBoardController implements Controller {
	public GetBoardController(){
		System.out.println("===>GetBoardController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		 System.out.println("글 상세 조회 처리"); 
		  int seq= Integer.parseInt(request.getParameter("seq")) ;
		  
		  BoardDao   dao = new BoardDaoImpl();
		  dao.cnt(seq);
		  BoardVo m = dao.getBoard(seq);
		  HttpSession session = request.getSession();	  
		  session.setAttribute("m", m);
		  
		return "getBoard";
	}

}
-----------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

import java.util.List;

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

import com.springbook.biz.board.BoardDao;
import com.springbook.biz.board.BoardVo;
import com.springbook.biz.board.impl.BoardDaoImpl;

public class GetBoardListController implements  Controller {
	public GetBoardListController(){
		System.out.println("===>GetBoardListController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		 System.out.println("글 목록 검색 처리"); 
		 String searchCondition=request.getParameter("searchCondition");
		 String searchKeyword=request.getParameter("searchKeyword");

		  BoardVo vo = new BoardVo();
		  vo.setSearchCondition(searchCondition);
		  vo.setSearchKeyword(searchKeyword);
		  
		  BoardDao   dao = new BoardDaoImpl();
		  List<BoardVo> li = dao.getBoardList(vo);
		  HttpSession session = request.getSession();
		  session.setAttribute("li", li);
		 
		return "getBoardList";
	}

}
------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

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

import com.springbook.biz.board.BoardDao;
import com.springbook.biz.board.BoardVo;
import com.springbook.biz.board.impl.BoardDaoImpl;

public class InsertBoardController implements Controller  {
	public InsertBoardController(){
		System.out.println("===>InsertBoardController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		 System.out.println("글 등록 처리"); 
		 
		   // 1. 사용자 입력 정보 추출
		   // request.setCharacterEncoding("UTF-8");
		   String title=request.getParameter("title");
		   String writer=request.getParameter("writer");
		   String content=request.getParameter("content");

		   // 2. DB연동 처리
		   BoardVo vo = new BoardVo();
		   vo.setTitle(title);
		   vo.setWriter(writer);
		   vo.setContent(content);
		   
		   BoardDao dao = new BoardDaoImpl();
		   dao.insert(vo);
		  	
		return "getBoardList.do";
	}

}
---------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

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

import com.springbook.biz.user.UserVo;
import com.springbook.biz.user.impl.UserDao3;

public class LoginController implements Controller  {
	public LoginController(){
		System.out.println("===>LoginController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("로그인 처리"); 
		 
		  String id=request.getParameter("id");
		  String password=request.getParameter("password");
		  

		   UserVo vo = new UserVo();
		   vo.setId(id);
		   vo.setPassword(password);
		   
		   UserDao3 service = new UserDao3();
		   UserVo user = service.getUser(vo);

		   if(user != null){
			  return "getBoardList.do";
		   }else{
			   return "login.jsp";
		   }
		   		
	}

}
--------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

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

public class LogoutController implements Controller {
	public LogoutController(){
		System.out.println("===>LogoutController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		 System.out.println("로그아웃 처리");
		 HttpSession session = request.getSession();
		 session.invalidate();		 
		return "login.jsp";
	}

}
-------------------------------------------------------------------------------------------------------------------------

​

package com.springbook.view.controller;

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

import com.springbook.biz.board.BoardDao;
import com.springbook.biz.board.BoardVo;
import com.springbook.biz.board.impl.BoardDaoImpl;

public class UpdateBoardController implements Controller{
	public UpdateBoardController(){
		System.out.println("===>UpdateBoardController");
	}
	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
		   // request.setCharacterEncoding("UTF-8");
		   int seq= Integer.parseInt(request.getParameter("seq")) ;
		   String title=request.getParameter("title");
		   String content=request.getParameter("content");

		   // 2. DB연동 처리
		   BoardVo vo = new BoardVo();
		   vo.setSeq(seq);
		   vo.setTitle(title);
		   vo.setContent(content);
		   
		   BoardDao dao = new BoardDaoImpl();
		   dao.update(vo);
		  
		   
		return "getBoardList.do";
	}

}


'Spring' 카테고리의 다른 글

Spring MVC 구조  (0) 2022.09.26
EL / JSTL 사용하기  (0) 2022.09.23
Model 2 : DispatcherServlet 만들기  (0) 2022.09.23
Model 1 아키텍처로 게시판 개발  (0) 2022.09.23
트랜잭션 처리  (0) 2022.09.22
Comments