SessionTo set a session:
session.setAttribute( "x", "John" );
"x" is sesseion's name, and "John" is session's value.
You can replace them with anything.
To get a session:
out.println session.getAttribute("x");
If you already set a value "John" for the session, then the output
is "John".
You can use session to track users. For example, you can set sessions in second.JSP
to track user name and password:
<%
String u=request.getParameter("user");
String p=request.getParameter("pass");
session.setAttribute( "user", u);
session.setAttribute( "pass", p);
%>
To protect a client page from other users, we can use Session and Redirect.
Let's add two lines in second.JSP and modify it as:
<%
String u=request.getParameter("user");
String p=request.getParameter("pass");
session.setAttribute( "user", u);
session.setAttribute( "pass", p);
if ((u.equals("John")) && (p.equals("John123"))){
response.sendRedirect "john.JSP";
}else if ((u.equals("Mike")) && (p.equals("Mike456"))) {
response.sendRedirect "mike.JSP";
}else if ((u.equals("Joe")) && (p.equals("Joe789"))) {
response.sendRedirect "joe.JSP";
}else{
out.println "<html><body>Sorry, invalid login</body></html>";
}
%>
Let's modify john.JSP. Add the following code on the top of the page:
<%
String u=session.getAttribute("user");
String p=session.getAttribute("pass");
if ((u.equals("John")) && (p.equals("John123"))) {
}else{
response.sendRedirect "first.JSP";
}
%>
<html>
<body>
John's Web page.
</body>
</html>
The basic idea in the above session tracking is that, when an user enter
an user name and a password in first.JSP, the query strings are passed
to second.JSP where JSP sets session "user" and "pass"
with the value of the user name and password. The sessions can be retriaved
in the following page john.JSP. If in john.JSP, you can get values of
the session "user" and "pass", and the values match
what you defined: "John" and "John123", then the page
open, otherwise, you will be redirected to another page.
Test john.JSP. Open a new web browser, point url to john.JSP. Since there
are no sessions of user name and password, the page will redirect you
to first.JSP. So as you can see, only the user who entered the correct
user name and password can open the page.
|