对于serlet代码的优化---对于地址的派发
Java Servlet 动态方法调用:BaseServlet 示例
在Java Web开发中,使用Servlet处理不同的HTTP请求通常需要覆盖 doGet 和 doPost 方法。然而,通过创建一个基础的 BaseServlet 类,我们可以更灵活地处理各种请求类型,并根据请求的URL动态调用相应的方法。
代码实现
以下是一个简单的 BaseServlet 实现,它能够根据请求的URI动态调用对应的方法。
package com.itheima.web_20211015_122145.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取请求的URI
String url = req.getRequestURI();
// 提取方法名
int index = url.lastIndexOf("/") + 1;
String name = url.substring(index);
// 获取当前类的Class对象
Class<? extends BaseServlet> cls = this.getClass();
try {
// 查找并调用指定名称的方法
Method method = cls.getMethod(name, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, req, resp);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
解析代码
关键点解析
获取请求的URI:使用 req.getRequestURI() 获取完整的请求路径。
提取方法名:从URI中提取出方法名。例如,如果请求路径是 /yourapp/someMethod,则提取出 someMethod。
查找并调用方法:使用反射机制查找当前类中与提取出的方法名匹配的方法,并调用该方法。
异常处理
在查找和调用方法的过程中可能会遇到以下异常:
NoSuchMethodException:当找不到指定名称的方法时抛出。
InvocationTargetException:当被调用的方法抛出异常时抛出。
IllegalAccessException:当尝试调用私有方法或受保护的方法时抛出。
这些异常被捕获并包装成 RuntimeException 抛出,确保问题能够被及时发现和处理。
使用示例
假设你有一个继承自 BaseServlet 的类 MyServlet,并且定义了如下方法:
java
深色版本
public class MyServlet extends BaseServlet {
public void someMethod(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().write("Hello from someMethod");
}
public void anotherMethod(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().write("Hello from anotherMethod");
}
}
当你访问 /yourapp/someMethod 时,someMethod 方法会被调用;访问 /yourapp/anotherMethod 时,anotherMethod 方法会被调用。

浙公网安备 33010602011771号