Servlet优化之BaseServlet
生活随笔
收集整理的這篇文章主要介紹了
Servlet优化之BaseServlet
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
BaseServlet
????1.我們希望在一個Servlet中可以有多個請求處理方法
????2、客戶端發送請求時,必須多給出一個參數,用來說明要調用的方法
????3、參數名遵守約定
????4、希望幫助簡化重定向和轉發,利用返回值
????????我們知道,Servlet中處理請求的方法是service()方法,這說明我們需要讓service()方法去調用其他方法。例如調用add()、mod()、del()、all()等方法!具體調用哪個方法需要在請求中給出方法名稱!然后service()方法通過方法名稱來調用指定的方法。
????????無論是點擊超鏈接,還是提交表單,請求中必須要有method參數,這個參數的值就是要請求的方法名稱,這樣BaseServlet的service()才能通過方法名稱來調用目標方法。例如某個鏈接如下:
????????????????<a href=”/xxx/CustomerServlet?method=add”>添加客戶</a>
代碼如下:
package cn.yfy.utils;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 {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {req.setCharacterEncoding("utf-8");res.setContentType("text/html;charset=utf-8");//獲取method參數,決定要調用的方法String methodName = req.getParameter("method");if (methodName == null || methodName.trim().isEmpty()) {throw new RuntimeException("您沒有傳遞參數,無法確定要調用的方法");}/** 通過反射獲取方法的反射對象并完成調用*/Class c = this.getClass();Method method = null;try {method = c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);} catch (Exception e) {throw new RuntimeException("您要調用的方法" + methodName + "()不存在");}// 獲取返回值,通過返回值完成轉發或重定向String text = null;try {text = (String) method.invoke(this, req, res);} catch (Exception e) {System.out.println("您調用的方法" + methodName+ "(HttpServletRequest,HttpServletResponse) 內部拋出了異常");throw new RuntimeException(e);}if (text == null || text.trim().isEmpty())return;if (!text.contains(":")) {req.getRequestDispatcher(text).forward(req, res);} else {int index = text.indexOf(":");String bz = text.substring(0, index);String path = text.substring(index + 1);if (bz.equalsIgnoreCase("r")) {res.sendRedirect(path);} else if (bz.equalsIgnoreCase("f")) {req.getRequestDispatcher(path).forward(req, res);} else {throw new RuntimeException("您的指定:" + bz + "暫時沒有開通此業務");}}}}下面為Servlet繼承該BaseServlet的代碼演示
package cn.yfy_01;import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import cn.yfy.utils.BaseServlet;public class BServlet extends BaseServlet {public String method1(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("調用了method1方法");//重定向到http://www.baidu.comreturn "r:http://www.baidu.com";}public String method2(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("調用了method2方法");//轉發到index.jspreturn "f:/index.jsp";} }若要調用響應的方法,需要在Servlet后面添加參數method決定調用哪個方法。
總結
以上是生活随笔為你收集整理的Servlet优化之BaseServlet的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jdbc入门(二)
- 下一篇: Java-Web 监听器和过滤器