Using SendRedirect() in Java Servlets
How to Redirect User from one page to another in Java
ServletsHome
sendRedirect is a method available in HttpServletResponse Interface, allows you to forward the response to another resource.
Syntax:
response.sendRedirect("path");
A relative URL can be used as a path argument.
Login.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="form1" method="post" action="SendRedirect">
Enter UserName:<input type=textbox name="username" value=""><br>
Enter Password:<input type=textbox name="password" value=""><br>
<input type=submit name="Login" ><br>
</form>
</body>
</html>
The above form will take the user details and redirects to servlet.
Servlet reads user values and validates the user. If valid, send him
to Userhome.html which greets with wecome message.
If not validated just shows "Invalid Login Details".
Page1 Output
SendRedirect.java
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class SendRedirect extends javax.servlet.http.HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals("admin")&& password.equals("admin")) { response.sendRedirect("Userhome.html"); } else { pw.println("Invalid Login Details"); } } }
Userhome.html <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> </body> <h1> Welcome User!!</h1> </body> </html>
Page2 Output:
Comments
Post a Comment