IndexAction.java
package com.gym.user.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.gym.user.service.impl.MatchServiceImpl;
public class IndexAction extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* 訪問根目錄默認跳轉到index.jsp
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MatchServiceImpl matchServiceImpl = new MatchServiceImpl();
List list = (List) matchServiceImpl.queryMatch();
RequestDispatcher dispatcher = request
.getRequestDispatcher("index.jsp");
request.setAttribute("matchList", list);
dispatcher.forward(request, response);
}
}
控制器中的doGet一般只負責顯示頁面,也就是調用各個模塊的jsp文件;doPost一般只負責數據的處理,以及跳轉到成功或失敗頁面。上面代碼中的matchServiceImpl.queryMatch();就是調用賽事服務組件中的查詢賽事方法,把返回的list對象放到request對象中,供jsp模板遍歷輸出,遍歷代碼如下:
<c:forEach items="${requestScope.matchList}" var="list">
<li> <span class="title"><a href="match/index.html?mid=${list.getmId() }">${list.getmName()} </a> </span> <span class="time">${list.getmDate()}</span> </li>
</c:forEach>
以上的控制器只是負責顯示主頁,但其他模塊的控制器需要執行不同的操作,比如用戶控制器,需要執行顯示用戶信息頁面,顯示修改密碼頁面,修改密碼,修改個人信息等動作,這就需要一個標記來判斷需要執行哪一個動作了。用String action = request.getParameter("action");獲取用戶需要執行的動作,然後判斷if(action.equals("xxx")) { },分別寫對應執行的代碼即可。由於java1.6以及之前的版本都不支持switch中使用String來匹配,所以用了比較笨的辦法,一個個判斷,例如用戶控制器:
UserAction.java
......
本文轉自:廣東海洋大學體育館管理系統 開發日記(11)——控制器(Action) - 雲代碼空間http://yuncode.net/article/a_5108a2e7b17f252