Java web----BaseServlet,web----baseservlet
1 BaseServlet的作用
在開始客戶管理系統之前,我們先寫一個工具類:BaseServlet。
我們知道,寫一個項目可能會出現N多個Servlet,而且一般一個Servlet只有一個方法(doGet或doPost),如果項目大一些,那麼Servlet的數量就會很驚人。
為了避免Servlet的“膨脹”,我們寫一個BaseServlet。它的作用是讓一個Servlet可以處理多種不同的請求。不同的請求調用Servlet的不同方法。我們寫好了BaseServlet後,讓其他Servlet繼承BaseServlet,例如CustomerServlet繼承BaseServlet,然後在CustomerServlet中提供add()、update()、delete()等方法,每個方法對應不同的請求。
2 BaseServlet分析
我們知道,Servlet中處理請求的方法是service()方法,這說明我們需要讓service()方法去調用其他方法。例如調用add()、mod()、del()、all()等方法!具體調用哪個方法需要在請求中給出方法名稱!然後service()方法通過方法名稱來調用指定的方法。
無論是點擊超連結,還是提交表單,請求中必須要有method參數,這個參數的值就是要請求的方法名稱,這樣BaseServlet的service()才能通過方法名稱來調用目標方法。例如某個連結如下:
<a href=”/xxx/CustomerServlet?method=add”>添加客戶</a>
3 代碼執行個體
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <servlet-name>AServlet</servlet-name> <servlet-class>cn.itcast.web.servlet.AServlet</servlet-class> </servlet> <servlet> <servlet-name>BServlet</servlet-name> <servlet-class>cn.itcast.web.servlet.BServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AServlet</servlet-name> <url-pattern>/AServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>BServlet</servlet-name> <url-pattern>/BServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
package cn.itcast.web.servlet;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 BaseServlet extends HttpServlet {public void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {/* * 1. 擷取參數,用來識別使用者想請求的方法 * 2. 然後判斷是否哪一個方法,是哪一個我們就調用哪一個 */String methodName = req.getParameter("method");if(methodName == null || methodName.trim().isEmpty()) {throw new RuntimeException("您沒有傳遞method參數!無法確定您想要調用的方法!");}/* * 得到方法名稱,是否可通過反射來調用方法? * 1. 得到方法名,通過方法名再得到Method類的對象! * * 需要得到Class,然後調用它的方法進行查詢!得到Method * * 我們要查詢的是當前類的方法,所以我們需要得到當前類的Class */Class c = this.getClass();//得到當前類的class對象Method method = null;try {method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);} catch (Exception e) {throw new RuntimeException("您要調用的方法:" + methodName + "(HttpServletRequest,HttpServletResponse),它不存在!");}/* * 調用method表示的方法 */try {String result = (String)method.invoke(this, req, resp);/* * 擷取請求處理方法執行後返回的字串,它表示轉寄或重新導向的路徑! * 幫它完成轉寄或重新導向! *//* * 如果使用者返回的是字串為null,或為"",那麼我們什麼也不做! */if(result == null || result.trim().isEmpty()) {return;}/* * 查看返回的字串中是否包含冒號,如果沒有,表示轉寄 * 如果有,使用冒號分割字串,得到首碼和尾碼! * 其中首碼如果是f,表示轉寄,如果是r表示重新導向,尾碼就是要轉寄或重新導向的路徑了! */if(result.contains(":")) {// 使用冒號分割字串,得到首碼和尾碼int index = result.indexOf(":");//擷取冒號的位置String s = result.substring(0, index);//截取出首碼,表示操作String path = result.substring(index+1);//截取出尾碼,表示路徑if(s.equalsIgnoreCase("r")) {//如果首碼是r,那麼重新導向!resp.sendRedirect(req.getContextPath() + path);} else if(s.equalsIgnoreCase("f")) {req.getRequestDispatcher(path).forward(req, resp);} else {throw new RuntimeException("你指定的操作:" + s + ",目前的版本還不支援!");}} else {//沒有冒號,預設為轉寄!req.getRequestDispatcher(result).forward(req, resp);}} catch (Exception e) {System.out.println("您調用的方法:" + methodName + ", 它內部拋出了異常!");throw new RuntimeException(e);}}}
package cn.itcast.web.servlet;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 在這裡給出多個請求處理方法 * 請求處理方法:除了名稱以外,都與service方法相同! * @author cxf * */public class AServlet extends BaseServlet {public void addUser(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("addUser()...");throw new IOException("測試一下");}public void editUser(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("editUser()...");}public void deleteUser(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("deleteUser()...");}public void loadUser(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("loadUser()...");}public void findAll(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("findAll()...");}}
package cn.itcast.web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BServlet extends BaseServlet {public String fun1(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("fun1()...");return "/index.jsp";}public String fun2(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("fun2()...");return "r:/index.jsp";}public String fun3(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("fun3()...");return "d:/WEB-INF/files/a.rmvb";}}