servlet檔案夾下隻有一個BaseServlet類;
一.BaseServlet
在實際調用的時候BaseServlet作為其他servlet類的父類使用,在該類中有隻有一個service()方法。
使用該類的好處在于,不必為每個方法都寫以一個對應的servlet類,可以将多個servlet請求放在一個servlet中進行處理
初級方法:
引用大佬的代碼:
public class actionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//擷取請求攜帶的method方法參數
String methodName = request.getParameter("method");
if("add".equals(methodName)){
add();
}else if("del".equals(methodName)){
del();
}else if("update".equals(methodName)){
update();
}else if("find".equals(methodName)){
find();
}
}
//查詢
private void find() {
//執行service層代碼
}
//更新
private void update() {
//執行service層代碼
}
//删除
private void del() {
//執行service層代碼
}
//添加
private void add() {
//執行service層代碼
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
這樣還是很麻煩,是以進化出了進階級方法如下;
引用大佬的話:
需要讓BaserServlet繼承于HttpServlet
反射的知識:(從第二步到第四步)
第一步:先擷取請求攜帶的方法參數值
第二步:擷取指定類的位元組碼對象
第三步:根據請求攜帶的方法參數值,再通過位元組碼對象擷取指定的方法
第四步:最後執行指定的方法
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);
}
}
}
在實際應用中該類作為以一個父類出現,所有的頁面請求通過該類處理後,找到其對應的在繼承該父類的子類中的方法;
該類的的第三個方法(最後一個try,catch)用來集中處理子類方法中的轉發和重定向。
附帶大佬的連結:https://blog.csdn.net/u010452388/article/details/80723550