Servlet:BaseServelt

1.在一个Servlet中可以有多个请求处理方法.

BaseServlet.java

package com.tinstu.units;

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 BaseServletf extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String methodName = request.getParameter("method");
		System.out.println(methodName);
		if(methodName == null && methodName.trim().isEmpty()) {
			throw new RuntimeException("你还没有提供method参数,不知道要调用哪个方法!");
		}
		
		Class c = this.getClass();
		
		Method method = null;
		
		try {
			method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("你要调用的方法:" + methodName + ",不存在!");
		}
		/*
		 * 调用method表示方法
		 */
		
		try {
			String result = (String) method.invoke(this, request, response);
			/*
			 * 获取请求处理方法执行后返回的字符串,它表示转发或者重定向的路径!
			 * 帮他完成转发或者重定向
			 */
			/*
			 * 查看返回的字符串是否含义冒号,如果没有,表示转发
			 * 如果有,使用冒号分割字符串,得到前缀和后缀
			 * 前缀放= f,转发,前缀= r 重定向. 后缀为路径
			 */
			
			if(result == null && result.trim().isEmpty()) {
				return;
			}
			
			if(result.contains(":")) {   //f://
				int index = result.indexOf(":");
				String start = result.substring(0, index);
				String path = result.substring(index + 1);
				
				if(start.equals("f")) {   //转发
					request.getRequestDispatcher(path).forward(request, response);
				} else if (start.equals("r")) {   //重定向
					response.sendRedirect(request.getContextPath() + path);
				} else {
					throw new RuntimeException("你指定的操作:"+ start +",当前版本还不支持");
				}
			} else { //没有冒号默认转发
				request.getRequestDispatcher(result).forward(request, response);
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

jsp中如何调用 案例:

首先要让servlet继承这个BaseServlet.java   (extends BaseServlet)

<form action="<c:url value='/CustomerServlet' />" method="post">
	<!-- 向servlet传递一个名为method的参数,其值表示要调用servlet的哪一个方法 -->
	<input type="hidden" name="method" value="add">

add

阅读剩余
THE END