TIL

230214 [JSP, Servlet] (Controller)

하차모 2023. 2. 15. 10:42

1. Servlet Controller

  서블릿으로 이동하는 페이지의 확장자명을 모두 .do로 하고 WebServlet 어노테이션을 사용하면 기능을 담당하는 Controller 서블릿 하나만 만들어 사용할 수 있다.

 

- first.jsp 파일

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="firstToSecond.do">첫번째 페이지</a>
</body>
</html>

 

- Controller 서블릿

// * : 에스테리스크 -> 전체(all)
//.do로 끝나는 요청을 다 받음
@WebServlet("*.do")
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public Controller() {
        super();  
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
	
	
	public void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		//한글 인코딩
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		
		//어떤 페이지에서 요청이 왔는지 -> command에 들어 있음
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		System.out.println("command = " + command);
		
		//응답 페이지
		String page = "";
		
		//first.jsp에서 서블릿 실행되었을 때
		if(command.equals("/firstToSecond.do")) {
			//필요한 기능..~~~
			page = "second.jsp";
		}
		
		//second.jsp에서 서블릿 실행되었을 때
		if (command.equals("/secondToThird.do")) {
			//필요한 기능..~~~
			page = "third.jsp";
			
		}
        
		//페이지 이동(page 변수에 들어 있는 주소로 이동함)
		RequestDispatcher dispatcher = request.getRequestDispatcher(page);
		dispatcher.forward(request, response);		
	}
}

 

- second.jsp 파일

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>두번째 페이지 입니다.</h3>
<a href="secondToThird.do">세번째 페이지로 이동</a>
</body>
</html>