爱编程
用代码编织自己的梦想

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 ");
    }
}
赞(0)
本网站所发布的所有内容源于互联网搬运,本站资源仅供个人学习交流,不允许用于商业用途,否则法律问题自行承担。仅限于小范围内传播学习和文献参考,请您在下载后24小时内删除,如有侵权请第一时间联系站长删除,敬请谅解! E-mail:admin@quange.cc

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址