juniorDeveloper
juniorDeveloper

Reputation: 225

Forwarding a request from one servlet to another using Request dispatcher

I was trying to create a cookie in one servlet , add it to response() and forwarded it to another servlet using DisaptcherServlet and tried to retrive the cookie using request.getCookies(). But this always coming out to be null.

//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");
}
}

Upvotes: -1

Views: 2588

Answers (1)

mmulholl
mmulholl

Reputation: 291

When you forward a request you are basically saying "no I don't want to process this request give it to this other resource instead". This means the forwarded request uses the same request and response as the original request.

In your example servlet one sets a cookie on the response, which welcome servlet cannot access because there is no API on the response object to get cookies. If you want this pattern servlet one should set a parameter on the request object which welcome servlet can then get from the request object.

Upvotes: 1

Related Questions