본문 바로가기

Servlet/Controller in MVC

Controller Servlet example

Reflection API 를 적용한 Controller Servlet example


브라우저 파리미터 cmd 값에 따라서 서비스 클래스의 해당 메소드가 호출되도록 한 콘트롤러 서블릿의 예이다

package org.java.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/EmpServlet")
public class EmpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cmd = request.getParameter("cmd");
		EmpService svc = new EmpService(request);
		String viewPath = null;
		if(cmd==null || cmd.equals("") ) cmd = "list";
		try {
			Method method = svc.getClass().getMethod(cmd);
			viewPath = (String) method.invoke(svc);
			request.getRequestDispatcher(viewPath).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}