RequestDispatcher disp = request.getRequestDispatcher("one.view");
使用include()
RequestDispatcher 的 include(),可以將另外一個Servlet的執行流程包含在目前Servlet的執行流程中。如下:
One.java
Two.java
在網頁看到的回應順序如下:
One.java
RequestDispatcher 的 include(),可以將另外一個Servlet的執行流程包含在目前Servlet的執行流程中。如下:
One.java
@WebServlet("/one.view")
public class One extends HttpServlet {
private static final long serialVersionUID = 1L;
public One() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("First view Start");
RequestDispatcher disp = request.getRequestDispatcher("two.view");
disp.include(request, response);
out.println("First view End");
}
}
Two.java
@WebServlet("/two.view")
public class Two extends HttpServlet {
private static final long serialVersionUID = 1L;
public Two() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("This is second view");
}
}
在網頁看到的回應順序如下:
使用forward()
RequestDispatcher 有個forward()方法,呼叫的時候一樣傳入request和response兩個物件,將請求處理轉發給其他Servlet。
One.java
@WebServlet("/hello.do")
public class One extends HttpServlet {
private static final long serialVersionUID = 1L;
public One() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HelloModel model = new HelloModel();
String name = request.getParameter("name");
String message = model.sayMessage(name);
RequestDispatcher disp = request.getRequestDispatcher("message.view");
request.setAttribute("message", message);
disp.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
HelloModel.java
public class HelloModel {
private Map messages = new HashMap();
public HelloModel() {
messages.put("Eric","Hi");
messages.put("Arch","Where are you?");
}
public String sayMessage(String user){
return user+","+messages.get(user);
}
}
Two.java
@WebServlet("/message.view")
public class Two extends HttpServlet {
private static final long serialVersionUID = 1L;
public Two() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String template = "
%s
";
String html = String.format(template, (String)request.getAttribute("message"));
response.getWriter().print(html);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
執行時的結果
參考資料
- Servlet&JSP 教學手冊


沒有留言:
張貼留言