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. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="add.do">ADD</a> <br><br> <a href="query.do">QUERY</a> <br><br> <a href="delete.do">DELETE</a> <br><br> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns: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"> <servlet> <servlet-name>CustomerServlet</servlet-name> <servlet-class>MVCCases.CustomerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CustomerServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
3.编写CustomerServlet类,获取需要调用的方法, 并利用反射获取并调用对应的方法