《Struts2框架 》學習之Struts2 的引用(使用filter作爲控制器的MVC應用)

實現MVCModel,View,Controller)模式的應用程序由3大部分構成

-模型:封裝應用程序的數據和業務邏輯(POJO

-視圖:實現應用程序的信息顯示功能(JSP

-控制器:接受來自用戶的輸入,調用模型層,相應對應的試圖組件(Servlet,Filter

 

需求

具體實現:

Index.jsp:

<a href="product_input.action">save</a>

關鍵代碼ProductFilter:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//由於請求分別有product_input和product_save,所以需要解析請求地址,並做出相應的處理
		///1.獲取servletPath
		HttpServletRequest httpServletRequest=(HttpServletRequest) request;
		String postPath=httpServletRequest.getServletPath();
		String path=null;
		//2.若其等於/product_input.action
		if ("/product_input.action".equals(postPath)) {
			path="/input.jsp";
		}
		//3.若其等於/product_save.action
		else if ("/product_save.action".equals(postPath)) {
			//獲取請求參數
			String productName=httpServletRequest.getParameter("productName");
			String productDesc=httpServletRequest.getParameter("productDesc");
			String productPrice=httpServletRequest.getParameter("productPrice");
			//封裝到Product對象中
			Product product=new Product(productPrice, productName, productDesc);
			//把對象保存到域對象request中
			httpServletRequest.setAttribute("product", product);
			path="/show.jsp";
		}
		//轉發到相應的頁面
		if (path!=null) {
			httpServletRequest.getRequestDispatcher(path).forward(request, response);
			//加上return ,由於上面已經請求轉發了,所以不需要執行chain.doFilter(request, response);
			return;
		}
		chain.doFilter(request, response);
	}

input頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'input.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  <body>
  		Save:<br>
  		<form action="product_save.action">
  			productName:<input type="text" name="productName"><br>
  			productDesc:<input type="text" name="productDesc"><br>
  			productPrice:<input type="text" name="productPrice"><br>
  			<input type="submit" value="Add"><br>
  		</form>
  </body>
</html>

當我們在input頁面輸入完完數據提交後發起請求

ProductFilter對象攔截後解析,處理數據後保存到域對象後轉請求轉發到show.jsp

    

,最後show.jsp通過表達式顯示在頁面



總結:

確實可以用Filter作爲控制器的MVC,

使用FIlter的好處?

使用一個過濾器來作爲控制器可以方便的在應用程序裏對所有的資源進行訪問控制

Servlet  VS  Filter

1,servlet可以完成的Filter都可以完成。例如ServletConfigServletContext.

2,攔截資源卻不是Servlet所擅長的!Filter中有FilterChain,這個APIServlet中沒有

 

下篇正式是Struts2的,而Struts2正是使用Filter實現的


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章