I am developing a college project and i will try to explain my problem using a small example. Below there are 3 jsp pages (index.jsp , test.jsp , logged.jsp) and i want that if the user try to access logged.jsp directly by entering url http://localhost:8080/sessionTest/logged.jsp then he will be redirected to index.jsp.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form action ="test.jsp" method="post"> enter user id :<input type="text" name="user"> Enter password:<input type="password" name="pass"> <input type="submit" value="submit"> </form> </body> </html>
test.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% String user= request.getParameter("user"); String pass= request.getParameter("pass"); if(user.equals("snow")&& pass.equals("123")) { session.setAttribute("user", user); RequestDispatcher r = request.getRequestDispatcher("logged.jsp"); r.forward(request, response); } else { out.println("wrong pass or id"); } %> </body> </html>
logged.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% session = request.getSession(false); if(session==null) { response.sendRedirect("index.jsp"); } else{ out.println("welcome its old session"); } %> </body> </html>
please , help me with some code and explain how it works