package cn.itcast.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* BaseServlet用來作爲其它Servlet的父類
*
* @author qdmmy6
*
* 一個類多個請求處理方法,每個請求處理方法的原型與service相同! 原型 = 返回值類型 + 方法名稱 + 參數列表
*/
@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");//處理響應編碼
request.setCharacterEncoding("UTF-8");
/**
* 1. 獲取method參數,它是用戶想調用的方法 2. 把方法名稱變成Method類的實例對象 3. 通過invoke()來調用這個方法
*/
String methodName = request.getParameter("method");
Method method = null;
/**
* 2. 通過方法名稱獲取Method對象
*/
try {
method = this.getClass().getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要調用的方法:" + methodName + "它不存在!", e);
}
/**
* 3. 通過method對象來調用它
*/
try {
String result = (String)method.invoke(this, request, response);
if(result != null && !result.trim().isEmpty()) {//如果請求處理方法返回不爲空
int index = result.indexOf(":");//獲取第一個冒號的位置
if(index == -1) {//如果沒有冒號,使用轉發
request.getRequestDispatcher(result).forward(request, response);
} else {//如果存在冒號
String start = result.substring(0, index);//分割出前綴
String path = result.substring(index + 1);//分割出路徑
if(start.equals("f")) {//前綴爲f表示轉發
request.getRequestDispatcher(path).forward(request, response);
} else if(start.equals("r")) {//前綴爲r表示重定向
response.sendRedirect(request.getContextPath() + path);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}