package com.quan.web.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 替换HttpServlet, 根据请求的最后的最后一段路径,来进行方法分发
*/
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的路径
String requestURI = req.getRequestURI();
// 获取最后一段的请求路径
int index = requestURI.lastIndexOf('/');
String methodName = requestURI.substring(index + 1);
// 获取this 对象的 字节码对象class
Class<? extends BaseServlet> aClass = this.getClass();
// 获取方法的Method 对象
try {
Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
package com.quan.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(" selectAll ");
}
public void addAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(" addAll ");
}
}
评论区