一个Servlet处理N个请求可以用反射 (二)

本文介绍了一个基于URL模式的Servlet映射方法,并展示了如何通过反射机制动态调用Servlet中的不同方法来响应用户的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、web.xml配置文件

<servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

二、JSP页面

<a href="find.do"> Find</a>
	<p />
	<a href="add.do"> Add</a>
	<p />
   <a href="delete.do"> Delete</a>

三、Servlet页面

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		// 获得提交的路径 :/find.do
		String path = request.getServletPath();

		// 截取出query
		String methodName = path.substring(1, path.indexOf("."));

		// out.println(methodName);

		try {
			// 利用反射
			Method method = getClass().getDeclaredMethod(methodName,
					HttpServletRequest.class, HttpServletResponse.class);
			// 执行相应的方法
			method.invoke(this, request, response);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		out.flush();
		out.close();
	}

	private void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("add action!");

	}

	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("del  action!");

	}

	private void find(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("find  action!");

	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

效果图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值