zoukankan      html  css  js  c++  java
  • Java反射实现Servlet处理多个请求--server分发

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.lang.reflect.Method;
    
    @WebServlet(name = "BasicServlet")
    public abstract class BasicServlet extends HttpServlet {
        public  void fun(HttpServletRequest request,HttpServletResponse response){
            System.out.println("fun");
        }
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
    //这种反射自定义方法必须是public 的,不然反射不到。想反射protected、private方法
    还需要其他操作。

    自定义方法和doGet、doPost等方法不同时执行,去掉ifelse则可同时执行
    //查询是否调用自定义方法,method为参数,值为方法名 String methodName = request.getParameter("method"); //methodName为null则没有调用自定义方法,去除空格为空即调用的自定义方法为空 //说明没有调用自定义方法,则去试图调用doGet,doPost,等等do方法。 if (methodName == null || methodName.trim().isEmpty()) { System.out.println("Basicserver"); super.service(request, response); } else { //当确实调用自定义方法,则利用反射来调用方法, //先得到方法名。在得到Method类对象。因此需要得到Class,在调用他的方法查询得到Method //我们要查询当前类的方法,所有需要当前类的Class Class classname = this.getClass(); Method method = null; try { method = classname.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); } catch (Exception e) { throw new RuntimeException("调用的方法:" + methodName + "不存在"); } //!!!!!!!!!!!!!!调用method表示的方法 try { //正常调用:this.add(request,repsponse), // 反射调用method(this,request,response): 方法(对象,参数) //this调用method表示的方法,参数为request,response String result = (String) method.invoke(this, request, response); //获取请求处理方法,执行后返回的字符串,表示转发或重定向,帮他完成 //若result是null,或""则不处理 //查看返回的字符串是否有冒号,没有则不处理 if (result == null || result.trim().isEmpty()) return; else if (result.contains(":")) { //使用冒号分割字符串,得到前缀和后缀 int index = result.indexOf(":");//获取冒号位置 String before = result.substring(0, index); String path = result.substring(index + 1); if (before.equalsIgnoreCase("r")) {//前缀为r则是重定向 response.sendRedirect(request.getContextPath() + path); } else if (before.equalsIgnoreCase("f")) {//前缀为f为转发 request.getRequestDispatcher(path).forward(request, response); } else { throw new RuntimeException("操作无法完成!"); } } else { //返回的字符串没有冒号,则不执行操作 return; } } catch (Exception e) { System.out.println(methodName + " 方法调用异常!"); throw new RuntimeException("调用的方法:" + methodName + "内部抛出异常!"); } } }}

      

  • 相关阅读:
    2021.01.28 Rating赛 解题/补题报告
    2021.01.23 Rating赛 补题&解题报告
    ACM 实验室2020.11.08天梯赛练习*5
    6. Python 基础 dict 字典 查找方法 set() 集合 公共方法
    5. python 基础 list [] 列表 tuple () 元组
    4. python 操作字符串 字符串的一些方法
    3. python基础 转化字符类型 循环
    2. python 数据类型 格式化
    1. Python是编译性语言解释性语言 pyCharm 配置
    科二 教育教学知识与能力4
  • 原文地址:https://www.cnblogs.com/Demonfeatuing/p/9462578.html
Copyright © 2011-2022 走看看