1. 程式人生 > >在一個Servlet中處理多個請求方法

在一個Servlet中處理多個請求方法

1. 在一個Servlet中可以有多個請求處理方法!
2. 客戶端傳送請求時,必須多給出一個引數,用來說明要呼叫的方法
  請求處理方法的簽名必須與service相同,即返回值和引數,以及宣告的異常都相同!
3. 客戶端必須傳遞一個引數!

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AServlet extends HttpServlet {

	public void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*
		 * 1.獲取引數,識別使用者想請求的方法
		 */
		String methodName = req.getParameter("method");
		if(methodName.equals("addUser")) { addUser(req,res);}
		else if(methodName.equals("editUser")) { editUser(req,res);}
		else if(methodName.equals("deleteUser")) {deleteUser(req,res);}
		else if(methodName.equals("loadUser")) {loadUser(req,res);}
	}

	public void addUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("addUser()...");
	}
	
	public void editUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("editUser()...");
	}

	public void deleteUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("deleteUser()...");
	}
	
	public void loadUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("loadUser()...");
	}


}


service方法的引數與使用者想呼叫的方法的引數一致

http://localhost:8080/day0213_1/AServlet?method=deleteUser

但是每新增一個新方法,service中就需要多加一個else if語句,作以下改進:

public void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*
		 * 1.獲取引數,識別使用者想請求的方法
		 */
		String methodName = req.getParameter("method");
		if(methodName==null || methodName.isEmpty()){
			throw new RuntimeException("沒有傳遞method引數");
		}
		/*
		 * 得到方法名稱,通過反射呼叫方法
		 *   得到方法名,通過方法名得到Method類的物件!
		 */
		Class c=this.getClass();
		
		Method method=null;
		try {
			method =c.getMethod(methodName,
					HttpServletRequest.class,HttpServletResponse.class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("您呼叫的方法"+methodName+"不存在!");
		} 
		
		/*
		 * 呼叫method表示的方法
		 */
		try {
			method.invoke(this, req,res);
		} catch (Exception e) {
			System.out.println("您呼叫的方法"+methodName+"內部丟擲了異常");
			throw new RuntimeException (e);
		} 
	}