java customerservlet_JavaWeb--MVC案例1-------(2)多个请求对应一个Servlet

af59572ccaa7ed54d465aa153fdcd023.png

35e3e9cf5a22bc0038532385c3aa4f3c.png

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.

--%>

Title

ADD

QUERY

DELETE

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">

CustomerServlet

MVCCases.CustomerServlet

CustomerServlet

*.do

3.编写CustomerServlet类,获取需要调用的方法, 并利用反射获取并调用对应的方法

43481739935ec3f1558044f5e508427a.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值