java http请求分发_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 + "内部抛出异常!");

}

}

}}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值