Servlet 的致命的兩個缺點(面試題): ActionServlet的實現步驟: 1、創建Action介面 : 2、創建一個Action 重寫Action介面的處理方法: 3、創建ActionFilter過濾器(實現Filter介面 重寫 Filter生命周期的方法): 解析URI的getAct ...
Servlet 的致命的兩個缺點(面試題):
- web.xml 文件配置項比較多 原因:由於Servlet的增多,會產生大量的Servlet配置
- Servlet 具有容器依賴性 原因:servlet在處理get或post請求時,HttpServletRequest和HttpServletResponse對象由Web容器創建
ActionServlet的實現步驟:
1、創建Action介面 :
public interface Action { public String execute(HttpServletRequest request,HttpServletResponse response); }
2、創建一個Action 重寫Action介面的處理方法:
public class HelloWorld implements Action{ @Override public String execute(HttpServletRequest request, HttpServletResponse response) { System.out.println("action 訪問成功!"); //提示Action的處理方法被執行 return "index.jsp"; //返回要重定向的jsp地址 } }
3、創建ActionFilter過濾器(實現Filter介面 重寫 Filter生命周期的方法):
public class ActionFilter implements Filter{ private HttpServletRequest request = null; private HttpServletResponse response = null; @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //拿到Http的響應和請求對象 this.request = (HttpServletRequest)request; this.response = (HttpServletResponse)response; //獲取過濾到的Action 地址的URI String uri = this.request.getRequestURI(); //解析出來要訪問的Action的名字 String actionName = ActionUtil.getAction(uri); try { //利用反射機制創建要訪問的Action Action action = (Action)Class.forName("th.action."+actionName).newInstance(); //調用要訪問的Action的處理方法 並且把HTTP的響應和請求傳給Action String page = action.execute(this.request, this.response); //根據Action返回的page頁面名字進行重定向 this.request.getRequestDispatcher(page).forward(this.request, this.response); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void destroy() { // TODO Auto-generated method stub } }
解析URI的getAction()方法:
public class ActionUtil { public static String getActionName(String uri){ String[] str = uri.split("/"); String result = str[str.length-1].substring(0, str[str.length-1].indexOf(".")); return result; } }
4、在Web.xml配置Filter過濾器:
<filter> <filter-name>ActionFilter</filter-name> <filter-class>th.filter.ActionFilter</filter-class> </filter> <filter-mapping> <filter-name>ActionFilter</filter-name> <url-pattern>*.action</url-pattern> <!--根據尾碼以*.action結尾的地址來區別要訪問的是Action還是Servlet--> </filter-mapping>
5、創建一個測試jsp頁面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <a href="HelloWorld.action" >請求一個action</a> //通過href="*.action" 來區別訪問的是Sevlet還是Action </body> </html>