java-web学习-Servlet 优化

quange 2022-5-12 159 5/12
java-web学习-Servlet 优化
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 ");
    }
}
- THE END -
最后修改:2022年5月12日
0

版权声明:
一、本站致力于为软件爱好者提供国内外软件开发技术和软件共享,着力为用户提供优资资源。
二、本站提供的所有下载文件均为网络共享资源,请于下载后的24小时内删除。如需体验更多乐趣,还请支持正版。
三、我站提供用户下载的所有内容均转自互联网。如有内容侵犯您的版权或其他利益的,请编辑邮件并加以说明发送到站长邮箱。站长会进行审查之后,情况属实的会在三个工作日内为您删除。

共有 0 条评论