쌍용교육(JAVA)/MVC

쌍용교육 -JSP수업 55일차 MVC(2)

구 승 2024. 5. 8. 12:09

kr.web.mvc =>

Action

package kr.web.mvc;

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

public interface Action { //인터페이스를 만들지않고 class를 하고싶다면 추상클래스로 만들어서 사용하면된다.
	//추상메서드
	public String execute (HttpServletRequest request, HttpServletResponse response) throws Exception;
}

ListAction

package kr.web.mvc;

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

public class ListAction implements Action{ //implements는 인터페이스를 구현하는 클래스를 선언할 때 사용
//ListAction 클래스는 Action 인터페이스에 정의된 execute 메서드를 구현해야 한다.
	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

		//request에 데이터 저장
		request.setAttribute("message", "목록 페이지입니다.");
		//호출할 JSP 경로 반환
		return "/views/list.jsp";
	}

}

Views =>

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>목록</title>
</head>
<body>
	<h1>목록</h1>
	${message}
</body>
</html>

kr.web.mvc =>

DispatcherServlet.java

package kr.web.mvc;

import java.io.IOException;
import java.io.PrintWriter;

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

public class DispatcherServlet extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);

	}
	public void requestPro(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		
		Action com = null; //Action 인터페이스를 구현한 객체를 저장할 변수
		String view = null; //view는 jsp 경로
		
		String command = request.getParameter("command");
		
		if(command ==null || command.equals("list")) {
			com = new ListAction(); //ListAction 객체를 생성하여 com 변수에 할당. 이것은 목록을 보여주는 액션을 실행하겠다는 뜻
		}
		
		try {
			view = com.execute(request, response);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//forward 방식으로 view(jsp) 호출
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);////view는 jsp 경로이기 때문에 경로대신 view를 써준다.
		
		dispatcher.forward(request,response);
		
	}

}

 

WriteAction

package kr.web.mvc;

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

public class WriteAction implements Action{

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		//request에 데이터 저장
		request.setAttribute("insert", "글등록 완료");
		//JSP 경로 반환
		return "/views/write.jsp";
	}

}

Views =>

write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글등록</title>
</head>
<body>
	<h1>글 등록</h1>
	${insert}
</body>
</html>

kr.web.mvc => 

DispatcherServlet.java

package kr.web.mvc;

import java.io.IOException;
import java.io.PrintWriter;

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

public class DispatcherServlet extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);

	}
	public void requestPro(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		
		Action com = null; //Action 인터페이스를 구현한 객체를 저장할 변수
		String view = null; //view는 jsp 경로
		
		String command = request.getParameter("command");
		
		if(command ==null || command.equals("list")) {
			com = new ListAction(); //ListAction 객체를 생성하여 com 변수에 할당. 이것은 목록을 보여주는 액션을 실행하겠다는 뜻
		}else if(command.equals("write")) {
			com = new WriteAction();
		}
		
		try {
			view = com.execute(request, response);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//forward 방식으로 view(jsp) 호출
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);////view는 jsp 경로이기 때문에 경로대신 view를 써준다.
		
		dispatcher.forward(request,response);
		
	}

}

kr.web.mvc => 

DetailAction.java

package kr.web.mvc;

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

public class DetailAction implements Action {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		//request에 데이터저장
		request.setAttribute("detail", "글 상세페이지 입니다.");
		//JSP 경로 반환
		return "/views/detail.jsp";
	}

}

Views =>

detail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 상세</title>
</head>
<body>
	<h1>글 상세</h1>
	${detail}
</body>
</html>

kr.web.mvc => 

DispatcherServlet.java

package kr.web.mvc;

import java.io.IOException;
import java.io.PrintWriter;

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

public class DispatcherServlet extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);

	}
	public void requestPro(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		
		Action com = null; //Action 인터페이스를 구현한 객체를 저장할 변수
		String view = null; //view는 jsp 경로
		
		String command = request.getParameter("command");
		
		if(command ==null || command.equals("list")) {
			com = new ListAction(); //ListAction 객체를 생성하여 com 변수에 할당. 이것은 목록을 보여주는 액션을 실행하겠다는 뜻
		}else if(command.equals("write")) {
			com = new WriteAction();
		}else if(command.equals("detail")) {
			com = new DetailAction();
		}
		
		try {
			view = com.execute(request, response);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//forward 방식으로 view(jsp) 호출
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);////view는 jsp 경로이기 때문에 경로대신 view를 써준다.
		
		dispatcher.forward(request,response);
		
	}

}

 

주소바꾸기

http://localhost:8080/ch03_JSP/dispatcher?command=detail (현주소)

detail.jsp (jsp주소)
http://localhost:8080/ch03_JSP/dispatcher?command=detail.do (바꾸는것이 목표인 주소이름)
http://localhost:8080/ch03_JSP/dispatcher?command=list.do

 

web.xml 을 수정하면됨.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">

<display-name>ch03_JSP</display-name>

<!-- 응답 상태 코드별 에러 페이지 지정 -->

<error-page>

<error-code>404</error-code>

<location>/ch06_errorPage/error/error404.jsp</location>

</error-page>

<error-page>

<error-code>500</error-code>

<location>/ch06_errorPage/error/error500.jsp</location>

</error-page>

<!-- 에러 타입별 에러 페이지 지정 -->

<error-page>

<exception-type>java.lang.NullPointerException</exception-type>

<location>/ch06_errorPage/error/errorNullPointer.jsp</location>

</error-page>

<!-- 세션 유지 시간 지정(분단위로 지정) -->

<session-config>

<session-timeout>50</session-timeout>

</session-config>

<!-- DispatcherServlet 설정 -->

<servlet>

<servlet-name>DispatcherServlet</servlet-name>

<servlet-class>kr.web.mvc.DispatcherServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>DispatcherServlet</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.jsp</welcome-file>

<welcome-file>default.htm</welcome-file>

</welcome-file-list>

</web-app>

 

<url-pattern>/dispatcher</url-pattern>

이 부분을

<url-pattern>*.do</url-pattern>

이렇게 수정한다.

kr.web.mvc => 

DispatcherServlet.java 부분도 수정

package kr.web.mvc;

import java.io.IOException;
import java.io.PrintWriter;

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

public class DispatcherServlet extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);

	}
	public void requestPro(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		
		Action com = null; //Action 인터페이스를 구현한 객체를 저장할 변수
		String view = null; //view는 jsp 경로
		
		String command = request.getRequestURI(); //.getRequestURI():클라이언트가 요청한 URI(Uniform Resource Identifier)를 반환
		System.out.println("1:"+command); //결과=> 1:/ch03_JSP/list.do 이를 컨텍스트 경로 라고한다.(list.do html에서 새로고침해서 list.do로 나온것)
		
		//indexOf 메서드는 문자열 내에서 특정 문자열 또는 문자의 인덱스를 반환
		//request.getContextPath()는 현재 웹 애플리케이션의 컨텍스트 경로를 알아내고 반환 ex:"/list.do"를 반환
		if(command.indexOf(request.getContextPath())==0) { //command 안에있는 문자열중 request.getContextPath())==0 의 문자열이 시작되는 인덱스를 반환
			
			//substring 메서드는 문자열에서 지정된 범위의 부분 문자열을 반환
			command = command.substring(request.getContextPath().length()); ///ch03_JSP/list.do의 길이를 알아내서 잘라내는부분
			System.out.println("2:"+command); //결과=>2:/list.do
		}
		
		if(command.equals("/list.do")) {
			com = new ListAction();
		}else if(command.equals("/write.do")) {
			com = new WriteAction();
		}else if(command.equals("/detail.do")) {
			com = new DetailAction();
		}
		
		try {
			view = com.execute(request, response);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//forward 방식으로 view(jsp) 호출
		//RequestDispatcher:서블릿 컨테이너에서 요청을 다른 자원(서블릿, JSP 등)으로 전달하는데 사용되는 인터페이스.
		//RequestDispatcher 는 forward와 include 2가지 메서드를 제공한다.
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);////view는 jsp 경로이기 때문에 경로대신 view를 써준다.
		
		//forward는 서블릿 컨테이너 내에서 서블릿이나 JSP가 처리하는 요청을 다른 서블릿이나 JSP로 전달하는 기능을 제공
		dispatcher.forward(request,response);
		
	}

}

UpdateAction.java

package kr.web.mvc;

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

public class UpdateAction implements Action {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//request의 데이터 저장
		request.setAttribute("update", "글 수정을 완료했습니다.");
		//JSP 경로 반환
		return "/views/update.jsp";
	}

}

update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 수정</title>
</head>
<body>
	<h1>글수정</h1>
	${update}
</body>
</html>

kr.web.mvc => 

DispatcherServlet.java

package kr.web.mvc;

import java.io.IOException;
import java.io.PrintWriter;

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

public class DispatcherServlet extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);

	}
	public void requestPro(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		
		Action com = null; //Action 인터페이스를 구현한 객체를 저장할 변수
		String view = null; //view는 jsp 경로
		
		String command = request.getRequestURI(); //.getRequestURI():클라이언트가 요청한 URI(Uniform Resource Identifier)를 반환
		System.out.println("1:"+command); //결과=> 1:/ch03_JSP/list.do 이를 컨텍스트 경로 라고한다.(list.do html에서 새로고침해서 list.do로 나온것)
		
		//indexOf 메서드는 문자열 내에서 특정 문자열 또는 문자의 인덱스를 반환
		//request.getContextPath()는 현재 웹 애플리케이션의 컨텍스트 경로를 알아내고 반환 ex:"/list.do"를 반환
		if(command.indexOf(request.getContextPath())==0) { //command 안에있는 문자열중 request.getContextPath())==0 의 문자열이 시작되는 인덱스를 반환
			
			//substring 메서드는 문자열에서 지정된 범위의 부분 문자열을 반환
			command = command.substring(request.getContextPath().length()); ///ch03_JSP/list.do의 길이를 알아내서 잘라내는부분
			System.out.println("2:"+command); //결과=>2:/list.do
		}
		
		if(command.equals("/list.do")) {
			com = new ListAction();
		}else if(command.equals("/write.do")) {
			com = new WriteAction();
		}else if(command.equals("/detail.do")) {
			com = new DetailAction();
		}else if(command.equals("/update.do")) {
			com = new UpdateAction();
		}
		
		try {
			view = com.execute(request, response);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//forward 방식으로 view(jsp) 호출
		//RequestDispatcher:서블릿 컨테이너에서 요청을 다른 자원(서블릿, JSP 등)으로 전달하는데 사용되는 인터페이스.
		//RequestDispatcher 는 forward와 include 2가지 메서드를 제공한다.
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);////view는 jsp 경로이기 때문에 경로대신 view를 써준다.
		
		//forward는 서블릿 컨테이너 내에서 서블릿이나 JSP가 처리하는 요청을 다른 서블릿이나 JSP로 전달하는 기능을 제공
		dispatcher.forward(request,response);
		
	}

}

 

DeleteAction.java

package kr.web.mvc;

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

public class DeleteAction implements Action{

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//request에 데이터 저장
		request.setAttribute("delete", "글 삭제 완료~~~~");
		//JSP경로반환
		return "/views/delete.jsp";
	}

}

delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 삭제</title>
</head>
<body>
	<h1>글 삭제</h1>
	${delete}
</body>
</html>

kr.web.mvc => 

DispatcherServlet.java

package kr.web.mvc;

import java.io.IOException;
import java.io.PrintWriter;

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

public class DispatcherServlet extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		requestPro(request,response);

	}
	public void requestPro(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		
		Action com = null; //Action 인터페이스를 구현한 객체를 저장할 변수
		String view = null; //view는 jsp 경로
		
		String command = request.getRequestURI(); //.getRequestURI():클라이언트가 요청한 URI(Uniform Resource Identifier)를 반환
		System.out.println("1:"+command); //결과=> 1:/ch03_JSP/list.do 이를 컨텍스트 경로 라고한다.(list.do html에서 새로고침해서 list.do로 나온것)
		
		//indexOf 메서드는 문자열 내에서 특정 문자열 또는 문자의 인덱스를 반환
		//request.getContextPath()는 현재 웹 애플리케이션의 컨텍스트 경로를 알아내고 반환 ex:"/list.do"를 반환
		if(command.indexOf(request.getContextPath())==0) { //command 안에있는 문자열중 request.getContextPath())==0 의 문자열이 시작되는 인덱스를 반환
			
			//substring 메서드는 문자열에서 지정된 범위의 부분 문자열을 반환
			command = command.substring(request.getContextPath().length()); ///ch03_JSP/list.do의 길이를 알아내서 잘라내는부분
			System.out.println("2:"+command); //결과=>2:/list.do
		}
		
		if(command.equals("/list.do")) {
			com = new ListAction();
		}else if(command.equals("/write.do")) {
			com = new WriteAction();
		}else if(command.equals("/detail.do")) {
			com = new DetailAction();
		}else if(command.equals("/update.do")) {
			com = new UpdateAction();
		}else if(command.equals("/delete.do")) {
			com = new DeleteAction();
		}
		
		try {
			view = com.execute(request, response);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//forward 방식으로 view(jsp) 호출
		//RequestDispatcher:서블릿 컨테이너에서 요청을 다른 자원(서블릿, JSP 등)으로 전달하는데 사용되는 인터페이스.
		//RequestDispatcher 는 forward와 include 2가지 메서드를 제공한다.
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);////view는 jsp 경로이기 때문에 경로대신 view를 써준다.
		
		//forward는 서블릿 컨테이너 내에서 서블릿이나 JSP가 처리하는 요청을 다른 서블릿이나 JSP로 전달하는 기능을 제공
		dispatcher.forward(request,response);
		
	}

}