โ 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>");
}
}
}
<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>