• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparision between redirect and forward

 
Sreenath Madasu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi y'all!
I just started preparing for SCWCD1.4 with one of the nicest and enjoyable books, HFS&J.
When I was going through the chapter of redirecting request, I had a doubt. You guys have given comparion between redirect and forward. But when do we use redirect and when do we use forward? What are adv/disadv of each? Could you please clarify?

Thanks
Sreenath Madasu
 
Mikalai Zaikin
Ranch Hand
Posts: 3334
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sreenath,

1. HttpServletResponse.sendRedirect(...)

- sends response to client with redirect headers
- can transfer client on any other web application
- not transparent for client (redirection happens in 2 steps)
- user sees in browser's address field the URL which application redirects to

[more info]

2. RequestDispatcher.forward(...)

- forwards request and response objects internally in Servlet Container to other resourse
- safe to pass to next servlet any object as request attribute
- can transfer client only within the same web application (servlet context)
- transparent for the client (redirection happens in 1 step)
- user sees original URL in address field, but output produced by another servlet/JSP

[more details]

regards,
MZ
 
Mikalai Zaikin
Ranch Hand
Posts: 3334
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another difference is that 'forward' allows to invoke servlets which are not accessible for user:
1) some password protected resource without using password
2) some resourse in /WEB-INF directory, which also is not served to user

You can not do this using 'sendRedirect'

regards,
MZ
 
Sreenath Madasu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That means it is better to use forward most of the time if we are in the same app, since this happens in one step and user cannot see and book mark the URL.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic