(三)首頁處理
阿新 • • 發佈:2017-10-07
servlet todo dtd index函數 tty ges throw 對象 param
完成功能:登陸後直接進入index.jsp界面
1、導入index.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body><jsp:forward page="/index"></jsp:forward> //在web.xml </body> </html>
package com.louis.web.servlet; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 通用servlet */ public class BaseServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { try { //1獲取子類,創建子類或調用子類的時候,this代表的是子類對象 Class clazz = this.getClass(); System.out.println(this); //2獲取請求方法 String m = request.getParameter("method"); //如果方法為空。默認為index。於是每個servlet都要又index() if(m==null) { m = "index"; } System.out.println(m); //3獲取方法對象 Method method = clazz.getDeclaredMethod(m, HttpServletRequest.class,HttpServletResponse.class); //4讓方法執行,返回值為請求轉發的路徑 String s = (String)method.invoke(this, request,response); //5判斷s是否為空 if(s!=null) { request.getRequestDispatcher(s).forward(request, response); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } } public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return null; } }
package com.louis.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 和首頁相關的servlet */ public class IndexServlet extends BaseServlet { public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 去數據庫中查詢最新商品和熱門商品,將他們放入request域中請求轉發 return "/jsp/index.jsp"; } }
說明:
1、url中不帶方法即可進入首頁,所以在BaseServlet中要加一個判斷條件,如果沒有method方法就調用index函數
2、IndexServlet中的index重寫了BaseServlet中的index方法
問題:<jsp:forward>能自動請求麽?
打斷點看調用的是那個index
(三)首頁處理