两种通用Servlet的写法以及分析

第一种写法:使用斜杠/

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;

/*
 * 通用Servlet
 */
public class BaseServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求的uri参数,然后截取获得请求的方法名
String methodName =  request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
try {
//通过反射获取方需要执行的方法
Class clazz = this.getClass();
Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
//获取方法执行后所转发或者是重定向的路径//每一个Servlet中的方法执行后,基本上都会有一个返回值,即是跳转的路径
String path = (String)method.invoke(this, request,response);
if(path != null){
if(path.contains(request.getContextPath())){
//如果路径中包含工程名,则使用重定向方法
response.sendRedirect(path);
}else{
//不是重定向,则只能是转发
request.getRequestDispatcher(path).forward(request, response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

第二种写法:method方法

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;
/**
 * 通用的SErvlet的编写:
 */
public class BaseServlet extends HttpServlet{


@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 接收参数:
String methodName = req.getParameter("method");
if(methodName == null || "".equals(methodName)){
resp.getWriter().println("method参数为null!!!");
return;
}
// 获得子类的Class对象:
Class clazz = this.getClass();
// 获得子类中的方法了:
try {
Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
// 使方法执行:
String path = (String)method.invoke(this, req,resp);
if(path != null){
if(path.contains(request.getContextPath())){
//执行重定向
response.sendRedirect(path);
}else{
//执行转发
request.getRequestDispatcher(path).forward(request, response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

说明:第一种方法是使用截取uri请求的参数,来获取需要的方法名;第二种方法是直接获取方法名;然后在通过反射来执行获取的方法;最后在执行页面的跳转,先获取需要得到的路径,使用转发或者是重定向,可以判断该路径中是否包含工程名来区分;

分析:第一种使用斜杠的方法,相比第二种方法能够更加的简化代码,特别是在从页面中向后台传递参数时;第一种方法直接使用斜杠,然后后面跟上方法名,很简单并且实用;第二种方法则必须单独写一个method才能向后台传递参数;其他的比如页面的跳转都是一些复用性非常高的代码,把它一起提取到Servlet中,就大大滴简化了代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值