redirect|response
<黑咖啡 原創>
以下是一個購物單提交的jsp頁面(正確的)
<%@ page contentType="text/html" language="java" import="java.util.*,com.blackCoffee.shop.*,com.blackCoffee.util.*,com.blackCoffee.db.*" %>
<%@ page errorPage="/error.jsp" %>
<%
if(AssociatorSession.getSession(session)==null)
response.sendRedirect("/login.jsp"); //如果會員沒有登入就跳轉到登入頁面,
else{ //如果已經登入則提交訂單並銷毀session中的購物車
Associator associator = new Associator();
associator = AssociatorSession.getSession(session);
String errmsg = "";
errmsg=OrderFormOperation.addOrderForm(request,session);
CartSession.removeSession(session); //銷毀session中的購物車
if(!errmsg.equals(""))
response.sendRedirect("/error.jsp?errmsg="+errmsg);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<Script language=JavaScript>
alert(" 以上商品已訂購,我們會和你及時聯絡!");
window.location="../index.jsp";
</Script>
</body>
</html>
<%}%>
有問題的代碼是這樣的
<%@ page contentType="text/html" language="java" import="java.util.*,com.blackCoffee.shop.*,com.blackCoffee.util.*,com.blackCoffee.db.*" %>
<%@ page errorPage="/error.jsp" %>
<%
if(AssociatorSession.getSession(session)==null)
response.sendRedirect("/login.jsp"); //如果會員沒有登入就跳轉到登入頁面,
//沒有else了
Associator associator = new Associator();
associator = AssociatorSession.getSession(session);
String errmsg = "";
errmsg=OrderFormOperation.addOrderForm(request,session);
CartSession.removeSession(session); //銷毀session中的購物車
if(!errmsg.equals(""))
response.sendRedirect("/error.jsp?errmsg="+errmsg);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<Script language=JavaScript>
alert(" 以上商品已訂購,我們會和你及時聯絡!");
window.location="../index.jsp";
</Script>
</body>
</html>
<%//}%>
請注意到出現問題的是因為沒有了else,問題如下:每當不登入就購買物品後,點“訂貨”提交按鈕,本來應該轉到登入頁面,登入後查看購物車,以前購買的貨物應該都在,但是點“訂貨”提交按鈕後,轉向登入頁面,登入後購物車裡沒有了。當時出現錯誤好像是說response.sendRedirect已經發送到用戶端,不能改變了,我就在這裡折騰了些時間,後來檢查代碼時發現了這句話CartSession.removeSession(session);
原來if(AssociatorSession.getSession(session)==null)
response.sendRedirect("/login.jsp"); //如果會員沒有登入就跳轉到登入頁面,
這句話後面沒有else, 所以頁面雖然跳轉了,但是後面的語句也繼續執行了,CartSession.removeSession(session);
這句清空了購物車,所以才會出錯。
總結:response.sendRedirect跳轉後,原頁面的語句會繼續執行。