2016-09-27 127 views
-1

我試圖在一個servlet中創建一個cookie,將它添加到response()並使用DisaptcherServlet將其轉發到另一個servlet,並嘗試使用request.getCookies( )。但是這總是出現爲空。使用請求調度程序將請求從一個servlet轉發到另一個

//Servlet one 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

String userName = request.getParameter("username"); 
String password = request.getParameter("password"); 

Cookie cookie = new Cookie("name", "value"); 
cookie.setMaxAge(30); 
response.addCookie(cookie); 

if(userName.equals("username") && password.equals("*****")){ 

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Welcome"); 
requestDispatcher.forward(request, response); 
} 
else{ 
System.out.println("invalid credentials"); 
} 
} 

//welcome servlet 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
Cookie [] cookie = request.getCookies(); 

if(cookie != null){ 
System.out.println("sucess"); 
} 
else{ 
System.out.println("cookieis null"); 
} 
} 

回答

1

當你轉發一個請求時,你基本上說「不,我不想處理這個請求,而是把它改爲這個其他資源」。這意味着轉發的請求使用與原始請求相同的請求和響應。

在您的示例servlet中,在響應中設置了一個cookie,該響應是受歡迎的servlet無法訪問的,因爲響應對象上沒有API來獲取cookie。如果你想要這個模式的servlet,你應該在request對象上設置一個參數,然後servlet可以從請求對象中獲得這個參數。

相關問題