两种通用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中,就大大滴简化了代码。

猜你喜欢

转载自blog.csdn.net/dengyilang123/article/details/54766992