- Java EE Tutorials
- JSP Tutorials
- Recommended Books for Java Server Pages (JSP)
Redirect is used to move or redirect response to another resource. The resource may be servlet , jsp or html file. In this tutorial we will see an example of how to redirect in JSP. We can do PageRedirect using the sendRedirect() method, which works at client side. It always sends a new request. It can be used within and outside the server.
sendRedirect() Syntax
Public void sendRedirect(String url)throws IOException
sendRedirect Example
This example performs following things:
- Write hello.html which contains forms to enter username and password. Enter userid and password and click on submit button. The control will be forwarded to pageredirectexample.jsp
- In pageredirectexample.jsp, a if username=”hello” and password=”world”, then the page is redirected to success.html
- If the username and password do not match then control goes failure.html.
Listing 1: hello.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="pageredirectexample.jsp" method="POST"> Enter Name: <input type="text" name="name"><br /> Enter password: <input type="password" name="pwd" /> <input type="submit" value="Submit" /> </form> </body> </html>
Listing 2: pageredirectexample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Page Redirect Example</title> </head> <body> <% String name = request.getParameter("name"); String password = request.getParameter("pwd"); if(name.equals("hello") && password.equals("world")) { response.sendRedirect("success.html"); } else { response.sendRedirect("failure.html"); } %> </body> </html>
Listing 3: success.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Successful Login</title> </head> <body> <h2>Welcome!!!!!.Successful login</h2> </body> </html>
Listing 4: failure.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Failure Login</title> </head> <body> Sorry...name and password are not correct!!!!! </body> </html>
Execute the hello.html. Right click on hello.html and select Run > Run As. Following output would be seen:
Enter correct user name password and following success screen would appear.
Enter invalid user name password and following failure screen would appear.
Previous Tutorial : JSP Implicit Objects || Next Tutorial : JSP API