Go to page using Redirect
One of the most used features of response is Redirect feature.
What is Redirect? It is Web server telling web browser to go to another page.
For example, there are many pages where after successful login, it automatically goes to main page. After running a specific page like login page, you can use redirect feature to automatically go to another specified page.
- Web browser sends request to a.jsp
- a. jsp tells web browser to redirect to b.jsp
- web browser requests b.jsp
Likewise, redirect is web server telling web browser to go to specified page. So if there are a.jsp and b.jsp like above, web browser is substantially requesting twice.
Response can direct the web browser to be redirected by using the following method.
- response.sendRedirect(String location)
response.sendRedirect() method is mainly used in the following form.
For example, if you wish to move to first page after logging in, you can use the sendRedirect() method as follows:
After running a web browser, enter this URL.
http://localhost:8080/jsp_practice/login.jsp?memberId=madv
On the other hand, if the value of parameter entered in memberId is equal to “madvirus”, it will move to /jsp_practice and output index.jsp.
Here is index.jsp.
On the other hand, if the value of the parameter entered in memberId “madvirus” The results of this screen are generated in the index.jsp / jsp_practice as follows: Go to /jsp_practice/index.jsp will be output.
http://localhost:8080/jsp_practice/login.jsp?memberId=madvirus
Our example has web browser to go to a page located on the same server ,but we can also make it to move to a different server. For example, if I want it to redirect to my blog, just type the full URL as follows:
response.sendRedirect(“https://minjookwon.wordpress.com”);
Earlier, I said the value of parameter that is send to the web server has to be properly encoded. In other words, in order to include something other than alphabet, numbers, and letters to URL, we need to encode it. response.sendRedirect() method also requires proper encoding. For example, let’s say you want to have a value of parameter named “name” to be ‘자바’. (Means Java in Korean). In this case, you must enter a URL in the form of encoding ‘자바’.
/jsp_practice/index.jsp?name=%C05DA%B9%D9
If programmer have to work to change ‘자바’ to ‘% C05DA% B9% D9’, it will be pain the ass. Fortuantely, there is a java.net.URLEncoder class that does this for us. We can use URLEncoder.encode() method to encode value of parameter with specified character set. The following example illustrates the use of URLEncoder.encode().
Try to run http://localhost:8080/jsp_practice/redirectEncodingTest.jsp