Servle利用反射制作工具类tBaseServlet

package com.offcn.util;

import java.io.IOException;
import java.lang.reflect.Method;

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

public abstract class BaseServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException{

            // 获取参数, 用来识别用户想请求的方法
            String mark = req.getParameter("mark");

            // 判断该参数是否存在, 不存在,抛出异常
            if(mark == null || mark.trim().isEmpty()){
                throw new RuntimeException("您没有传递 mark 参数! 无法确定您想调用的方法");
            }

            //得到当前类的 class 对象
            Class<? extends BaseServlet> c = this.getClass();

            //通过查找本类这子类中的方法名称(不是get和set是值类中的方法)
            Method method = null;
            try{
                method = c.getMethod(mark,HttpServletRequest.class, HttpServletResponse.class);
            } catch(Exception e){
                throw new RuntimeException("您要调用的方法"+mark+",它不存在!");
            }

            //如果发现类中有这个方法通过反射调用那个对应的方法
            try{
                method.invoke(this,req,resp);  
            } catch(Exception e){                    
                throw new RuntimeException(e);
            }
    }
}
public class UserServlet extends BaseServlet{
	//Servlet直接继承BaseServlet 可以省去判断
	public void validate_phone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String phone_number = request.getParameter("phone_number");
		boolean b = us.validate_phone(phone_number);
		PrintWriter pw = response.getWriter();
		pw.print(b+"");
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值