DispatcherServlet

์ฝœ๋ผ๋ง˜ยท2023๋…„ 6์›” 27์ผ
0

JSP

๋ชฉ๋ก ๋ณด๊ธฐ
13/17
post-thumbnail

๐Ÿ DispatcherServlet

  • HTTP ํ”„๋กœํ† ์ฝœ๋กœ ๋“ค์–ด์˜ค๋Š” ๋ชจ๋“  ์š”์ฒญ์„ ๊ฐ€์žฅ ๋จผ์ € ๋ฐ›์•„ ์ ํ•ฉํ•œ ์ปจํŠธ๋กค๋Ÿฌ์— ์œ„์ž„ํ•ด์ฃผ๋Š” ํ”„๋ก ํŠธ ์ปจํŠธ๋กค๋Ÿฌ(Front Controller)
  • ์‡ผํ•‘๋ชฐ์˜ ์ธํฌ ๋ฐ์Šคํฌ์ฒ˜๋Ÿผ ์ž…๊ตฌ์—์„œ ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์žˆ๋‹ค๊ฐ€ ์š”์ฒญ์— ๋”ฐ๋ผ ๊ธธ์„ ์•ˆ๋‚ดํ•ด์ฃผ๋Š” ์—ญํ• 

๐Ÿคบ DispatcherServlet ์ž‘์„ฑ ์ˆœ์„œ

  1. ๋””์ŠคํŒจ์ณ ์„œ๋ธ”๋ฆฟ์„ ๋งŒ๋“ค๊ณ  HttpServlet์„ ์ƒ์†๋ฐ›๊ณ  init๊ณผ service๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œ ํ•ด์„œ ์‚ฌ์šฉํ•œ๋‹ค

โœ” DispatcherServlet.java (์˜ˆ์‹œ) >>

public class DispatcherServlet extends HttpServlet{
	private Map<String, RequestProcess> processMapping = new HashMap<>();
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		// config์—์„œ application scope๋ฅผ ๊บผ๋‚ด contextPath๋ฅผ ๊บผ๋ƒ„
		String contextPath = config.getServletContext().getContextPath();
		// ์–ด๋–ค ์ฃผ์†Œ + ์–ด๋–ค ์š”์ฒญ ๋ฐฉ์‹์œผ๋กœ ์ ‘์†ํ–ˆ์„ ๋•Œ ์–ด๋–ค ์ฒ˜๋ฆฌ๋ฅผ ํ•  ๊ฒƒ์ธ์ง€ ๋“ฑ๋ก
		processMapping.put(contextPath + "/hello::GET", new HelloProcess());
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 1. ์‚ฌ์šฉ์ž์˜ ์š”์ฒญ์„ ๋ฐ›๋Š”๋‹ค
		System.out.println("์‚ฌ์šฉ์ž๊ฐ€ ์š”์ฒญํ•œ URL : " + request.getRequestURL());
		System.out.println("์‚ฌ์šฉ์ž๊ฐ€ ์š”์ฒญํ•œ URI : " + request.getRequestURI());
		System.out.println("์š”์ฒญ ๋ฐฉ์‹ : " + request.getMethod());

		try {
			// 2. ์š”์ฒญํ•œ URI์™€ Method์— ๋งž๋Š” ์ฒ˜๋ฆฌ๋ฅผ ์ง„ํ–‰ํ•œ๋‹ค (๊ฐ์ฒด์ง€ํ–ฅํ™”)
			// 		-> uri์™€ method๋กœ ์•Œ๋งž์€ RequestProcess๋ฅผ ๊ณจ๋ผ process()๋ฅผ ์‹คํ–‰์‹œํ‚จ๋‹ค
			String nextPage = processMapping.get(request.getRequestURI() + "::" + request.getMethod()).process(request, response);
			
			// 3. ์ฒ˜๋ฆฌ ํ›„ ์•Œ๋งž์€ view ํŽ˜์ด์ง€๋กœ ํฌ์›Œ๋“œ ํ•˜๊ฑฐ๋‚˜ redirectํ•œ๋‹ค
			if(nextPage.startsWith("redirect:")) {
				response.sendRedirect(nextPage.substring("redirect:".length()));
			}else {
			request.getRequestDispatcher("/WEB-INF/views" + nextPage + ".jsp").forward(request, response);
			}
		}catch(NullPointerException e) {
			response.getWriter().append("<html><script>history.back();</script></html>");
		}
	}
}
  1. web.xml์—์„œ servlet, servlet-mapping ์ž‘์„ฑ
<servlet>
  	<servlet-name>appServlet</servlet-name>
  	<servlet-class>servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
  
<!--์ด ๊ฒฝ๋กœ๋กœ ๋“ค์–ด์˜ค๋Š” ๋ชจ๋“  ์š”์ฒญ์— ๋Œ€ํ•ด DispatcherServlet์œผ๋กœ ๊ฐ€์žฅ๋จผ์ € ๋“ค์–ด์˜ค๋„๋ก ํ•œ๋‹ค-->
  <servlet-name>appServlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
profile
์ฝœ๋ผ๋ง˜ ์ฝ”๋”ฉ์ผ๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€