URL Rewriting and URL Encoding in JSP Servlet

You often need to encode URL before sending it to server and need to rewrite URL with session id in order to maintain session where cookie is not present. here are some more differences between URL-rewriting and URL encoding in Servlet JSP

1) java.servlet.http.HttpServletResponse methods encodeURL(String url) and encodeRedirectURL(String URL) is used to encode SesssionID on URL to support URL-rewriting. don't confuse with name encodeURL() because it doesn't do URL encoding instead it embeds sessionID in url if necessary. logic to include sessionID is in method itself and it doesn't embed sessionID if browser supports cookies or session maintenance is not required. In order to implement a robust session tracking all URL from Servlet and JSP should have session id embedded on it.

In order to implement URL-rewriting in JSP you can use use JSTL core tag all URL passed to it will automatically be URL-rewriting if browser doesn't support cookies.

While java.net.URLEncoder.encode() and java.net.URLDecoder.decode()is used to perform URL Encoding and decoding which replace special character from String to another character. This method uses default encoding of system and also deprecated instead of this you can use java.net.URLEncoder.encode(String URL, String encoding) which allows you to specify encoding. as per W3C UTF-8 encoding should be used to encode URL in web application.

2) In URL rewriting session id is appended to URL and in case of URL-encoding special character replaced by another character.