baseservlet怎么写_BaseServlet

软件简介

BaseServlet 是个类似 struts 的功能的小工具类,一个Servlet中可以有多个请求处理方法。

客户端发送请求时,必须多给出一个参数,用来说明要调用的方法,请求处理方法的返回值和参数须与service有相同,以及声明的异常都相同。

客户端必须传递名为method的参数。

String name = request.getParameter("method");

if (name == null || name.trim().isEmpty()) {

throw new RuntimeException("你好,你没有输入方法参数");

}

Class c = this.getClass();

Method method = null;

try {

method = c.getMethod(name, HttpServletRequest.class,

HttpServletResponse.class);

} catch (Exception e) {

throw new RuntimeException("你好,你要调用的方法" + name + ",不存在");

}

try {

String result = (String) method.invoke(this, request, response);

/*

* 获取请求处理方法执行后返回的字符串,它表示转发或重定向的路径! 帮它完成转发或重定向!

*/

/*

* 如果用户返回的是字符串为null,或为"",那么我们什么也不做!

*/

if (result == null || result.trim().isEmpty()) {

return;

}

/*

* 查看返回的字符串中是否包含冒号,如果没有,表示转发 如果有,使用冒号分割字符串,得到前缀和后缀!

* 其中前缀如果是f,表示转发,如果是r表示重定向,后缀就是要转发或重定向的路径了!

*/

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);//项目名+index.jsp组合成完整的路径

//重定向要完整的路径,转发则不需要完整的路径只需要/index.jsp即可。

} else if (s.equalsIgnoreCase("f")) {// 如果前缀是F,那么转发!

request.getRequestDispatcher(path).forward(request,

response);

} else {

throw new RuntimeException("对不起,你要访问的方法版本不支持!");

}

} else {// 没有冒号,默认为转发!

request.getRequestDispatcher(result).forward(request, response);

}

} catch (Exception e) {

System.out.println("你好,你调用的方法,内部出现了异常");

throw new RuntimeException(e);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值