BaseServlet 利用反射定位方法


BaseServlet 原理

1. BaseServlet

package com.regino.test;

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.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取客户调用的方法
        String action = request.getParameter("action"); // 获取要调用的方法名
        try {
            // 获取当前类的字节码对象
        /*
          getDeclaredMethod(methodName,Class types)
                参数1:方法名
                参数2:方法的参数类型
         */
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            //为了防止方法是私有的,可以使用暴力反射
            method.setAccessible(true);
        /*
          invoke(obj,args)
            obj: 调用方法的对象
            args: 调用该方法需要的实参
         */
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

2. UserServlet

  • 继承 BaseServlet 后直接写方法就可以了。
package com.regino.travel.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.regino.travel.domain.ResultInfo;
import com.regino.travel.domain.User;
import com.regino.travel.service.UserService;
import com.regino.travel.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {

    // 注册
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ...
    }
}

原文链接:https://qwert.blog.csdn.net/article/details/106248363

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试
应支付0元
点击重新获取
扫码支付

支付成功即可阅读