回顧: 關於跳轉之前就強調過有兩種:
1. 客戶端跳轉: 地址欄跳轉之後改變,而且無法傳遞request范圍的屬性,是在所有的操作執行完畢之後才發生跳轉的操作,語法:request.sendRedirect()
2.服務器端跳轉: 地址欄不改變,而且可以傳遞request范圍的屬性,屬於無條件跳轉,只要執行到了,則立刻執行跳轉的操作。 語法:<jsp:forward>
Servlet之中也是可以完成跳轉的,而且既然Servlet本身已經存在了HttpServeltResponse對象,所以直接通過此對象的sendRedirect()方法可以完成跳轉操作。
客戶端跳轉
package ServletDemo;
import java.io.IOException;
import javax.print.attribute.standard.Sides;
import javax.servlet.*;
import javax.servlet.http.*;
public class kehuduanTiaozhuan extends HttpServlet { //繼承HttpServlet
public void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{ //處理服務
req.getSession().setAttribute("name", "趙玉強");
req.setAttribute("info","zhaoyuqiang.blog.51cto.com");//設置屬性
resp.sendRedirect("get_info.jsp");//設置跳轉的頁面
}
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{ //處理POST請求
this.doGet(req, resp); //調用doGet()方法
}
}
get_info.jsp
<%@ page language="java" contentType="text/html" pageEncoding="utf-8"%>
<html>
<head>
<title>WEB開發</title>
</head>
<body>
<% request.setCharacterEncoding("utf-8");%>
<h2>session屬性:<%=session.getAttribute("name") %></h2>
<h2>request屬性:<%=request.getAttribute("info") %></h2>
</body>
</html>