自制BaseServlet

本文介绍了一种在Servlet中利用反射技术动态调用不同请求处理方法的实现方式,并详细展示了如何根据请求参数选择并执行相应的业务逻辑。

一个Servlet中可以有多个请求处理方法,可以利用反射实现


package cn.day19.web.servlet;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {
    public void service(HttpServletRequest request,HttpServletResponse response){
        String methodName = request.getParameter("method");
        
        if(methodName ==null || methodName.trim().isEmpty()){
            throw new RuntimeException("无method参数!");
        }
        //通过反射调用名称
        Class c = this.getClass();//得到当前的class对象
        Method method = null;
        try {
            method =c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("方法不存在");
        }
        
        //调用method
            try {
                String result = (String)method.invoke(this, request,response);
                if(result == null || result.trim().isEmpty()) return;
                
                if(result.contains(":")){
                    int index = result.indexOf(":");//获取冒号的位置
                    String s = result.substring(0,index);//截取出前缀,表示操作
                    String path = result.substring(index+1);//截取后缀,表示路径
                    
                    if(s.equalsIgnoreCase("r")){        //如果前缀是r,那么重定向
                        response.sendRedirect(request.getContextPath()+path);
                    }else if(s.equalsIgnoreCase("f")){//f:转发
                        request.getRequestDispatcher(path).forward(request, response);
                    }else {
                        throw new RuntimeException("没有指定的"+s+"操作");
                    }
                }else{//没有冒号,默认为转发
                    request.getRequestDispatcher(result).forward(request, response);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                throw new RuntimeException();
            } 
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值