Monday 1 April 2013

Session Example in jsp


Session-exp.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <p align="center"><%if(request.getParameter("msg")!=null){out.print(request.getParameter("msg"));}%></p>
        <form action="validate.jsp" method="post">
        Name<input type="text" name="userid"/><br>
        Password<input type="password" name="pass"/><br>
        <input type="submit" name="submit" value="login"/>
        </form>  
        <h1>Hello World!</h1>
    </body>
</html>

home.jsp

<%
String user=(String)session.getAttribute("user");
if(user==null){
    response.sendRedirect("session-exp.jsp?msg=Invalid session");
}
%>
<%@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>
        <p><a href="logout.jsp">Logout</a><p>
        <h1>Welocome: <%=user%></h1>
    </body>
</html>

validate.jsp

<%
String userid=request.getParameter("userid");
String pass=request.getParameter("pass");
if(userid.equals("aman") && pass.equals("kumar")){
    session.setAttribute("user", userid);
    response.sendRedirect("home.jsp");
} else{
    response.sendRedirect("session-exp.jsp?msg=Invalid username or password.");
}
%>

logout.jsp

<%
session.invalidate();
response.sendRedirect("session-exp.jsp?msg=Logout successfully");
%>

No comments:

Post a Comment