BaseServlet
1.我们希望在一个Servlet中可以有多个请求处理方法
2、客户端发送请求时,必须多给出一个参数,用来说明要调用的方法
3、参数名遵守约定
4、希望帮助简化重定向和转发,利用返回值
我们知道,Servlet中处理请求的方法是service()方法,这说明我们需要让service()方法去调用其他方法。例如调用add()、mod()、del()、all()等方法!具体调用哪个方法需要在请求中给出方法名称!然后service()方法通过方法名称来调用指定的方法。
无论是点击超链接,还是提交表单,请求中必须要有method参数,这个参数的值就是要请求的方法名称,这样BaseServlet的service()才能通过方法名称来调用目标方法。例如某个链接如下:
<a href=”/xxx/CustomerServlet?method=add”>添加客户</a>
代码如下:
package cn.yfy.utils;
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 {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
//获取method参数,决定要调用的方法
String methodName = req.getParameter("method");
if (methodName == null || methodName.trim().isEmpty()) {
throw new RuntimeException("您没有传递参数,无法确定要调用的方法");
}
/*
* 通过反射获取方法的反射对象并完成调用
*/
Class c = this.getClass();
Method method = null;
try {
method = c.getMethod(methodName, HttpServletRequest.class,
HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要调用的方法" + methodName + "()不存在");
}
// 获取返回值,通过返回值完成转发或重定向
String text = null;
try {
text = (String) method.invoke(this, req, res);
} catch (Exception e) {
System.out.println("您调用的方法" + methodName
+ "(HttpServletRequest,HttpServletResponse) 内部抛出了异常");
throw new RuntimeException(e);
}
if (text == null || text.trim().isEmpty())
return;
if (!text.contains(":")) {
req.getRequestDispatcher(text).forward(req, res);
} else {
int index = text.indexOf(":");
String bz = text.substring(0, index);
String path = text.substring(index + 1);
if (bz.equalsIgnoreCase("r")) {
res.sendRedirect(path);
} else if (bz.equalsIgnoreCase("f")) {
req.getRequestDispatcher(path).forward(req, res);
} else {
throw new RuntimeException("您的指定:" + bz + "暂时没有开通此业务");
}
}
}
}
下面为Servlet继承该BaseServlet的代码演示
package cn.yfy_01;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.yfy.utils.BaseServlet;
public class BServlet extends BaseServlet {
public String method1(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("调用了method1方法");
//重定向到http://www.baidu.com
return "r:http://www.baidu.com";
}
public String method2(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("调用了method2方法");
//转发到index.jsp
return "f:/index.jsp";
}
}
若要调用响应的方法,需要在Servlet后面添加参数method决定调用哪个方法。