이안의 평일코딩

JSP 8일차 - Annotation 본문

Back-end/JSP

JSP 8일차 - Annotation

이안92 2020. 10. 13. 17:17
반응형

2020.10.13(화)

Java Resources/src/

com.sist.controller

RequestMapping.java

package com.sist.controller;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
/*
 *   메모리 유지 
 *   CLASS
 *   SOURCE
 *   ================ 컴파일후에 메모리 해제 
 *   RUNTIME
 *   ================ 컴파일후에도 메모리 유지
 */
@Target(METHOD)
/*
 *   Annotation 
 *    1. 기능이 없다 
 *    2. 찾기 
 *       = TYPE  ====> 클래스를 찾는 경우
 *       = PARAMETER => 매개변수를 찾는 경우
 *       = CONSTRUCTOR => 생성자 찾는 경우
 *       = FILED  => 멤버변수 찾는 경우
 *       = METHOD => 메소드 찾는 경우 
 *    ================================= 위치 (Annotation)
 *    @Annotation명  ==> TYPE
 *    public class MovieModel
 *    {
 *         @Annotation명  ==> FILED
 *         MovieDAO dao=new MovieDAO();
 *         
 *         @Annotation명  ==> CONSTRUCTOR
 *         public MovieModel(@Annotation명  ==> PARAMETER int a)
 *         {
 *         }
 *         @Annotation명  ==> METHOD
 *         public void display()
 *         {
 *         }
 *    }
 *    
 *    @RequestMapping("movie/list.do")  ==> Spring
 *    public String movieListData(HttpServletRequest request)
 */
public @interface RequestMapping {
   public String value(); // 문자열로 구분 
}

Controller.java

package com.sist.controller;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
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 java.util.*;
@WebServlet("*.do")
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private List<String> list=new ArrayList<String>();
	public void init(ServletConfig config) throws ServletException {
		list.add("com.sist.model.MovieModel");
		list.add("com.sist.model.ReserveModel");
		list.add("com.sist.model.MemberModel");
	}
   
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
				String cmd=request.getRequestURI();
				// /OnLineStudy17_MVC/movie/detail.jsp
				// movie/detail.do
				cmd=cmd.substring(request.getContextPath().length()+1);
				// Annotation찾는 방법 
				for(String strCls:list)
				{
				    // 메모리 할당 
					Class clsName=Class.forName(strCls);
					Object obj=clsName.newInstance();
					// 메소드 찾기
					Method[] methods=clsName.getDeclaredMethods();
					for(Method m:methods)
					{
						RequestMapping rm=m.getAnnotation(RequestMapping.class);
						// 어노테이션을 이용해서 해당 메소드 찾기
						if(cmd.equals(rm.value()))
						{
							// 해당 메소드 호출 
							String jsp=(String)m.invoke(obj, request);
							if(jsp.startsWith("redirect"))
							{
								// return "redirect:list.do"
								response.sendRedirect(jsp.substring(jsp.indexOf(":")+1));
							}
							else
							{
								// request를 전달 
								RequestDispatcher rd=request.getRequestDispatcher(jsp);
								rd.forward(request, response);
							}
							return;//service메소드 종료 
						}
					}
					
				}
		}catch(Exception ex){}
	}

}

 

MainClass.java

package com.sist.controller;
import java.lang.reflect.Method;
import java.util.*;
class A
{
	@RequestMapping("aaa.do")
	// 중복할 수 없다 ==> 어노테이션 => if문을 추가하는 것이다 
	public void aaa()
	{
		System.out.println("A:aaa() Call...");
	}
	@RequestMapping("bbb.do")
	public void bbb()
	{
		System.out.println("A:bbb() Call...");
	}
	@RequestMapping("ccc.do")
	public void ccc()
	{
		System.out.println("A:ccc() Call...");
	}
	@RequestMapping("ddd.do")
	public void ddd()
	{
		System.out.println("A:ddd() Call...");
	}
}
// aaa.do  ==> aaa() , bbb.do ==> bbb() ccc.do ==> ccc()
public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Scanner scan=new Scanner(System.in);
        System.out.print("사이트주소 입력:");// getRequestURI()
        String cmd=scan.next();
        
		/*
		 * A a=new A(); if(cmd.equals("aaa.do")) { a.aaa(); } else
		 * if(cmd.equals("bbb.do")) { a.bbb(); } else if(cmd.equals("ccc.do")) {
		 * a.ccc(); }
		 */
        try
        {
        	// 클래스의 모든 정보를 읽어 온다 
        	Class clsName=Class.forName("com.sist.controller.A");
        	// 메모리 할당 
        	Object obj=clsName.newInstance();
        	// A클래스가 가지고 있는 모든 메소드를 읽어 온다 
        	Method[] methods=clsName.getDeclaredMethods();
        	for(Method m:methods)
        	{
        		// System.out.println(m.getName());// A클래스에 선언되어 있는 메소드이름을 가지고 온다
        		// Method위에 있는 Annotation를 읽는다 
        		// 어노테이션을 프로그래머가 만드는 일은 거의 없다
        		RequestMapping rm=m.getAnnotation(RequestMapping.class);
        		// 어노테이션을 읽어오는 방법 
        		if(cmd.equals(rm.value()))
        		{
        			m.invoke(obj, null);// 메소드 이름을 몰라도 찾을 수 있다 
        			// invoke ==> 해당 메소드를 호출 과정 
        			// a.aaa()
        			// 메소드 호출 (obj(A클래스)가 가지고 있는 메소드를 호출한다)
        			// null ==> 매개변수
        		}
        	}
        }catch(Exception ex) {}
	}

}

 

com.sist.model

MemberModel.java

package com.sist.model;

import javax.servlet.http.HttpServletRequest;

import com.sist.controller.RequestMapping;

/*
 *   1. 회원가입
 *   2. 로그인 
 */
public class MemberModel {
	@RequestMapping("main/main.do")
	public String main_page(HttpServletRequest request)
	{
		return "../main/main.jsp";
	}
	@RequestMapping("member/join.do")
    public String memberJoin(HttpServletRequest request)
    {
    	request.setAttribute("msg", "회원가입");
    	request.setAttribute("main_jsp", "../member/join.jsp");
    	return "../main/main.jsp";
    }
	@RequestMapping("member/login.do")
    public String memberLogin(HttpServletRequest request)
    {
    	request.setAttribute("msg", "로그인");
    	request.setAttribute("main_jsp", "../member/login.jsp");
    	return "../main/main.jsp";
    }
}

MovieModel.java

package com.sist.model;

import javax.servlet.http.HttpServletRequest;

import com.sist.controller.RequestMapping;

// interface를 사용하지 않는다 (일반자바 => POJO)
// 전체 목록 출력
// 상세보기
public class MovieModel {
  @RequestMapping("movie/list.do")
  public String movieListData(HttpServletRequest request)
  {
	  request.setAttribute("msg", "영화목록");
	  // include에 포함될 jsp파일 전송
	  request.setAttribute("main_jsp", "../movie/list.jsp");
	  return "../main/main.jsp";// request를 전송할 jsp파일명 
  }
  @RequestMapping("movie/detail.do")
  public String movieDetailData(HttpServletRequest request)
  {
	  request.setAttribute("msg", "영화상세보기");
	  request.setAttribute("main_jsp", "../movie/detail.jsp");
	  return "../main/main.jsp";// request를 전송할 jsp파일명 
	  
	  //return "../movie/detail.jsp";// forward , sendRedirect (jsp => _ok.jsp)
	  
	  /*
	   *   1. 화면에 출력할 내용이 있는 경우 (request를 유지) ==> forward
	   *   2. 화면에 출력하는 내용이 아닌 경우 (데이터베이스 추가,수정,삭제) ==> 수행후에 sendRedirect() 다른 화면으로 이동
	   *      예) insert_ok.jsp ==> list.jsp
	   *          login_ok.jsp ==> main.jsp
	   *          
	   */
	  
  }
}

ReserveModel.java

package com.sist.model;

import javax.servlet.http.HttpServletRequest;

import com.sist.controller.RequestMapping;

/*
 *   1. 영화목록
 *   2. 극장목록
 *   ===========
 *   3. 날짜정보
 *   4. 시간정보
 *   5. 인원정보
 *   6. 예매정보 
 */
public class ReserveModel {
	 @RequestMapping("reserve/movie.do")
     public String movieList(HttpServletRequest request)
     {
    	 // 값전송(jsp) ==> request에 담아준다 
    	 request.setAttribute("msg", "예매=>영화정보");
    	 request.setAttribute("main_jsp", "../reserve/movie.jsp");
   	  	 return "../main/main.jsp";// request를 전송할 jsp파일명 
    	 //return "../reserve/movie.jsp";
     }
	 @RequestMapping("reserve/theater.do")
     public String theaterList(HttpServletRequest request)
     {
    	 request.setAttribute("msg", "예매=>극장정보");
    	 request.setAttribute("main_jsp", "../reserve/theater.jsp");
   	  	 return "../main/main.jsp";// request를 전송할 jsp파일명 
    	 //return "../reserve/theater.jsp";
     }
}

 

WebContent/

main.main.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>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <div class="row">
      <a href="../movie/list.do" class="btn btn-sm btn-primary">영화목록</a>
      <a href="../movie/detail.do" class="btn btn-sm btn-success">영화상세보기</a>
      <a href="../reserve/movie.do" class="btn btn-sm btn-warning">예매영화목록</a>
      <a href="../reserve/theater.do" class="btn btn-sm btn-info">예매극장목록</a>
      <a href="../member/join.do" class="btn btn-sm btn-danger">회원가입</a>
      <a href="../member/login.do" class="btn btn-sm btn-active">로그인</a>
    </div>
    <div class="row">
      <jsp:include page="${main_jsp }"></jsp:include>
    </div>
  </div>
</body>
</html>

 

member/join.jsp, login.jsp

movie/detail.jsp, list.jsp

reserve/movie.jsp, theater.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>
	<center>
		<h1>${msg }</h1>
	</center>
</body>
</html>

 

==========================================================================================

 

Java Resources/src/

com.sist.controller

DispatcherServlet.java

package com.sist.controller;

import java.io.*;
import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// DispatcherServlet : Spring 실제 Controller명
// XML에 등록된 클래스를 읽어서 메모리 할당 
import javax.xml.parsers.*;
import org.w3c.dom.*; //dom => 트리형태 
import java.util.*;
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	List<String> clsList=new ArrayList<String>();

	/*
	 *    1. web.xml
	 *        = Framework 
	 *        = Spring , Struts , 사용자 , jsf
	 *    2. server.xml
	 *    3. Model ======> DAO 
	 *    4. JSP
	 */
	public void init(ServletConfig config) throws ServletException {
		// web.xml에 등록된 내용을 읽기 시작 (ServletConfig)
		/*
		 *   <init-param>
		      <param-name>contextConfigLocation</param-name>
		      <param-value>
		        <!-- 설정된 XML파일의 경로 -->
		        C:\Users\채제분\git\online\OnLineStudy17_MVC2\WebContent\WEB-INF\application-context.xml
		      </param-value>
		    </init-param>
		 */
		/*
		 *    <servlet>
				  <servlet-name>salesServlet</servlet-name>
				  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
				  <!-- contextLoader가 해당 위치의 설정 파일을 읽어, 해당 파일을 dispatcher servlet으로 만든다. -->
				  <init-param>
				    <param-name>contextConfigLocation</param-name>
				    <param-value>/WEB-INF/salesServlet-servlet.xml</param-value>
				  </init-param>
				  <load-on-startup>1</load-on-startup>
				</servlet>
				
				<!-- /sales로 시작하는 url 요청을 받아 salesServlet에서 처리한다. -->
				<servlet-mapping>
				  <servlet-name>salesServlet</servlet-name>
				  <url-pattern>*.naver</url-pattern>
				</servlet-mapping>
				
				.jsp .asp .aspx .php
				
				a.do/admin/1234  ==> node.js
				a.do?id=admin&pwd=1234
		 */
		String path=config.getInitParameter("contextConfigLocation");
		System.out.println(path);
		
		// 파싱 
		try
		{
			DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();// 파싱하는 클래스 생성
			DocumentBuilder db=dbf.newDocumentBuilder();// 실제 XML파싱 
			// 파싱 => 메모리에 트리형태로 저장 ==> 필요한 데이터를 추가,수정,삭제,읽기
			// 파싱한 저장하는 공간 Document
			Document doc=db.parse(new File(path));
			// 최상위 태그 <beans> ==> 데이터베이스 (테이블)
			Element root=doc.getDocumentElement(); // root => beans
			// bean태그를 모아서 관리 ==> NodeList
			NodeList list=root.getElementsByTagName("bean");
			for(int i=0;i<list.getLength();i++)
			{
				Element bean=(Element)list.item(i); //bean태그를 한개씩 가지고 온다 
				String cls=bean.getAttribute("class");
				System.out.println(cls);
				clsList.add(cls);
			}
		}catch(Exception ex) {}
	}
    // 사용자가 요청할때 호출되는 메소드 => Model Class <==> JSP
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{
			// 사용자 요청값 받기  ==> movie/list.do
			String cmd=request.getRequestURI();
			// http://localhost/OnLineStudy17_MVC2/main/main.do  ==> URL
			// /OnLineStudy17_MVC2/main/main.do  ==> URI
			// /OnLineStudy17_MVC2  => ContextPath
			cmd=cmd.substring(request.getContextPath().length()+1);
			
			// 해당 모델 클래스를 찾는다 ==> 메소드를 호출한다 (invoke())
			// invoke() ==> 메소드는 프로그래머 마음대로 만들 수 있다
			for(String strCls:clsList) // clsList에 클래스명이 등록 (application-context.xml)
			{
				// 메모리 할당 
				// Class.forName() , new  ==> 리플렉션  
				// 리플렉션 ==> 클래스의 이름으로 정보를 읽어와서 제어 (젼수,메소드 호출...)
				// 단점 : OOP를 파괴
				Class clsName=Class.forName(strCls);
				Object obj=clsName.newInstance();
				// obj가 가지고 있는 메소드를 찾아서 호출 ==> request를 값을 담아준다 
				Method[] methods=clsName.getDeclaredMethods();
				// Annotation을 찾아서 밑에 있는 메소드를 호출 
				for(Method m : methods)
				{
					/*
					 *   @RequestMapping("main/main.do")
					 *   public String disp()
					 */
					RequestMapping rm=m.getAnnotation(RequestMapping.class);
					if(cmd.equals(rm.value()))
					{
						// invoke(Object obj, Object... args) => 다변매개변수 
						String jsp=(String)m.invoke(obj, request,response);
						
						// sendRedirect => request가 필요가 없는 경우 
						// forward => request에 들어가 있는 데이터 출력 
						// 화면 이동 
						if(jsp.startsWith("redirect"))
						{
							// return "redirect:list.do"
							// response
							response.sendRedirect(jsp.substring(jsp.indexOf(":")+1));
						}
						else
						{
							// return "main/main.jsp";
							// request전송 => RequestDispatcher
							RequestDispatcher rd=request.getRequestDispatcher(jsp);
							rd.forward(request, response);
						}
						return; // service 메소드 종료 
					}
				}
				
			}
		}catch(Exception ex) 
		{
			ex.printStackTrace();
		}
	}

}

 

Controller.java

package com.sist.controller;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(TYPE)
public @interface Controller {

}

 

RequestMapping.java

package com.sist.controller;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(METHOD)
public @interface RequestMapping {
  public String value();//String문자열로 구분 (찾기) => 구분자가 동일하면 안된다 
  // 메소드위에 => @RequestMapping("구분") => 찾는 내용 밑에 있다 
  // rm.value()
}

 

com.sist.model

MainModel.java

package com.sist.model;

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

import com.sist.controller.RequestMapping;

public class MainModel {
   @RequestMapping("main/main.do")
   public String main_page(HttpServletRequest request,HttpServletResponse response)
   {
	   request.setAttribute("main_jsp", "../main/home.jsp");
	   return "../main/main.jsp";
   }
}

 

WebContent/

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    response.sendRedirect("main/main.do");
%>

 

main/

home.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>
  <center>
    <h1>Home 페이지</h1>
  </center>
</body>
</html>

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1 <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li><a href="#">Page 1-1</a></li>
          <li><a href="#">Page 1-2</a></li>
          <li><a href="#">Page 1-3</a></li>
        </ul>
      </li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
  
<div class="container">
  <jsp:include page="${main_jsp }"></jsp:include>
</div>

</body>
</html>

 

WEB-INF/

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- application-context.xml
	 1. 프로그래머가 만든 클래스를 등록 파일
	 2. 클래스 => 패키지 등록
 -->
 <beans>
  <bean class="com.sist.model.MainModel"/>
  <bean class="com.sist.model.MovieModel"/>
 </beans>

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_3_1.xsd" version="3.1">
  <display-name>OnLineStudy17_MVC2</display-name>
  <servlet>
  	<servlet-name>dispatcher</servlet-name>
  	<servlet-class>com.sist.controller.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>
  			<!-- 설정된 XML파일의 경로 -->
  			/Users/yongpro/Desktop/OnLineStudy17_MVC2/WebContent/WEB-INF/application-context.xml
  		</param-value>
  	</init-param>
  </servlet>
  <!-- URL주소로 DispatcherServlet 찾기 -->
  <servlet-mapping>
  	<servlet-name>dispatcher</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

==========================================================================================

Java Resources/src/

com.sist.controller

ComponentScan.java

package com.sist.controller;
import java.util.*;
import java.io.*;
// /Users/yongpro/Desktop/OnLineStudy18_MVCFinal/src
// /Users/yongpro/Desktop/OnLineStudy18_MVCFinal/src/com/sist/model
public class ComponentScan {
	public List<String> fileConfig(String pack, String path){
		List<String> list = new ArrayList<String>();
		try {
			path=path+"/"+pack.replace(".", "/");
			File dir=new File(path);
			File[] files=dir.listFiles();
			for(File f:files) {
				//System.out.println(f.getName());
				String name=f.getName();
				String ext=name.substring(name.lastIndexOf(".")+1);
				if(ext.equals("java")) {
					String s=pack+"."+name.substring(0,name.lastIndexOf("."));
					//System.out.println(s);
					System.out.println("====="+pack+"=====");
    				System.out.println(s);
    				list.add(s);
				}
			}
			
		}catch(Exception ex) {}
		return list;
	}
	public static void main(String[] args) {
		ComponentScan cs=new ComponentScan();
		String pack="com.sist.model";
		String path="/Users/yongpro/Desktop/OnLineStudy18_MVCFinal/src";
		cs.fileConfig(pack, path);
	}
}

 

DispatcherServlet.java

package com.sist.controller;
import java.io.*;
import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
// /Users/yongpro/Desktop/JAVA1/HelloWorld/OnLineStudy18_MVCFinal/src
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// Model를 저장 => 사용자 요청 => 찾아주는 역할
	// Model class를 모아서 메모리 할당 => 찾기 
	List<String> clsList = new ArrayList<String>();
	public void init(ServletConfig config) throws ServletException {
		String xmlPath = config.getInitParameter("contextConfigLocation");
		String path=config.getInitParameter("path");
		System.out.println("xml-path:"+xmlPath);
		System.out.println("path:"+path);
		try {
			DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
			DocumentBuilder db=dbf.newDocumentBuilder(); // 파서기 생성
			Document doc=db.parse(new File(xmlPath));
			// 루트 태그
			Element root=doc.getDocumentElement();
			// 회원가입, 로그인(세션) => 상세 => 쿠키 => 찜하기, 예매처리
			NodeList list=root.getElementsByTagName("component-scan");
			ComponentScan com = new ComponentScan();
			for(int i=0; i<list.getLength(); i++) {
				Element cs=(Element)list.item(i);
				String pack=cs.getAttribute("base-package");
				List<String> cList=com.fileConfig(pack, path);
				for(String s:cList) {
					System.out.println(s);
					clsList.add(s);
				}
			}
		}catch(Exception ex) {}
		System.out.println("DispatcherServlet");
		for(String s:clsList) {
			System.out.println(s);
		}
	}
	// 요청 결과값 => 해당 JSP로 전송
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 메소드 찾아서 수행 => 결과값을 JSP로 전송
		// 사용자가 요청한 내용을 받는다
		// http://localhost
		String cmd=request.getRequestURI();
		// main/main.do
		cmd=cmd.substring(request.getContextPath().length()+1);
		// OnLineStudy18_MVCFinal/
		try {
			// 메모리 할당 (Model클래스 메모리 할당) => clsList
			// new MainModel() ==> Controller (한개) ==> 공유 (수정을 하면 => 유지보수가 어렵다) => 고정
			// XML => C/Java/C#/JavaScript
			for(String cls:clsList) {
				Class clsName=Class.forName(cls);
				Object obj=clsName.newInstance();
				// MainModel m=new MainModel();
				/*
				 *     class A
				 *     class B
				 *     
				 *     //A a=new A();
				 *    // a=new B();
				 *    Object obj=new A();
				 *    obj=new B();
				 */
				// 메소드를 찾아서 호출 (invoke())
				Method[] methods=clsName.getDeclaredMethods();
				// 클래스에 선언된 모든 메소드를 가지고 온다
				for(Method m:methods) {
					RequestMapping rm = m.getAnnotation(RequestMapping.class);
					if(cmd.equals(rm.value())) {
						String jsp=(String)m.invoke(obj, request);
								// a.display()
						if(jsp.equals("redirect")) {
							response.sendRedirect(jsp.substring(jsp.indexOf(":")+1));
							// return redirect:list.do
							// return "../main/main.jsp"
						}
						else {
							// request전송
							RequestDispatcher rd=request.getRequestDispatcher(jsp);
							rd.forward(request, response);
						}
						return; // 종료 (response=>사용자에게 데이터 전송시 한번만 수행)
					}
				}
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}

}

 

RequestMapping.java

package com.sist.controller;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(METHOD)
public @interface RequestMapping {
	// 구분 => 문자열 
	public String value();
	
}

 

com.sist.model

MainModel.java

package com.sist.model;
import javax.servlet.http.HttpServletRequest;
import com.sist.controller.*;
public class MainModel {
	@RequestMapping("main/main.do")
	public String main_page(HttpServletRequest request) {
		request.setAttribute("msg", "Main.jsp");
		return "../main/main.jsp";
	}
}

 

MovieModel.java

package com.sist.model;

import javax.servlet.http.HttpServletRequest;

import com.sist.controller.RequestMapping;

public class MovieModel {
	@RequestMapping("main/movie.do")
	public String main_page(HttpServletRequest request) {
		request.setAttribute("msg", "Main.jsp");
		return "../main/movie.jsp";
	}
}

 

com.sist.model2

MyPageModel.java

package com.sist.model2;

import javax.servlet.http.HttpServletRequest;

import com.sist.controller.RequestMapping;

public class MyPageModel {
	@RequestMapping("mypage/mypage.do")
	public String main_page(HttpServletRequest request) {
		request.setAttribute("msg", "MyPage.jsp");
		return "../mypage/mypage.jsp";
	}
}

 

WebContent/WEB-INF

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<component-scan base-package="com.sist.model"/>
	<component-scan base-package="com.sist.model2"/>
</beans>

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_3_1.xsd" version="3.1">
  <display-name>OnLineStudy18_MVCFinal</display-name>
  <servlet>
  	<servlet-name>dispatcher</servlet-name>
  	<servlet-class>com.sist.controller.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>/Users/yongpro/Desktop/OnLineStudy18_MVCFinal/WebContent/WEB-INF/application-context.xml</param-value>
  	</init-param>
  	<init-param>
  		<param-name>path</param-name>
  		<param-value>/Users/yongpro/Desktop/OnLineStudy18_MVCFinal/src</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>dispatcher</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

WebContent/main

main.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>
	<h1>${msg }</h1>
</body>
</html>

 

movie/

movie.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>
 <center>
 	<h1>${msg }</h1>
 </center>
</body>
</html>

 

반응형
Comments