反射实现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");
//自定义方法和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 + "内部抛出异常!"); } } }}

  

猜你喜欢

转载自www.cnblogs.com/Demonfeatuing/p/9462578.html