1.编写继承了HttpServlet类的CustomerServlet类,并重写doGet()和doPost()方法
package MVCCases;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
public class CustomerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doGet(req, resp);
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doPost(req, resp);
//1.获取servletPath:/add.do 或 /delete.do等
String servletPath = req.getServletPath();
//2.取出/和.do得到方法名
String methodName = servletPath.substring(1);
methodName = methodName.substring(0, methodName.length() - 3);
//3.利用反射获取methodName对应的方法
Method method = null;
try {
method = getClass().getDeclaredMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
//4.利用发射调用对应的方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
resp.sendRedirect("error.jsp");
}
}
private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("add");
}
private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("query");
}
private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("delete");
}
}
2.添加jsp和web.xml文件
Created by IntelliJ IDEA.
User: Skye
Date: 2017/12/10
Time: 11:10
To change this template use File | Settings | File Templates.
--%>
Titlexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
CustomerServlet
MVCCases.CustomerServlet
CustomerServlet
*.do
3.编写CustomerServlet类,获取需要调用的方法, 并利用反射获取并调用对应的方法