Maintain Session using URL Rewriting

In this method, we rewrite the URL and append the information to the URL to keep the track of the values. URL Rewriting can be used to maintain the session. We can maintain session using URL rewriting.

There are several methods to maintain session between client and server, see all types of method here

Lets see an example

—index.jsp—

How to maintain Session?

 


3.
URL rewriting

Once you click on the URL rewriting link URLRwriting.java class will append p3lang in the URL. See below code of URLRewriting.java

–rewrite.jsp–
This rewrite.jsp page is the response page. This page will display the value that we have sent in the URL.

OUTPUT:

Index page
URL Rewriting
Rewritten URL
URL Rewriting 1

Maintain Session using User Authorization

We can maintain session using User Authorization, the most common method.
Maintain Session using User Authorization is the second method in the series of http://p3lang.com/2014/06/playing-with-session-in-java/ post.

User Authorization is the most common way to maintain session between client and server.
A user has to sign-in into the application using their credentials. Once the user submits the form by filling the correct credentials a session gets created on the server that will be used during the entire user session.

Use these credentials to make this form work:
Email: session@session.com
Password: session

 
—index.jsp—
This page contains the login form.

 
—welcome.jsp—
If the user successfully logged in then, this welcome page will get displayed. This welcome page will display the hello message and email id of the user.

 
—error.jsp—

 
—Login.java—

 
—Logout.java—

 
OUTPUT:

User_Authorization_Login_page

In the above screenshot, you can see the login form. We haven’t logged in yet, the session present is the session that is by default assign by the Apache tomcat server to the browser.

Now let’s login with the credentials.

User_Authorization_Login_page_2

 
Using this method, We have set session in apache tomcat server not in cookies,

 
Below is the code snippet to display the session value on the webpage

Maintain Session using Cookies in jsp servlet

Session can be maintained using browser cookies.
Here in this post, we will see how to Maintain Session using Cookies in JSP servlet.

It is very simple to maintain session using cookies, you just need to create an object of Cookie Class then call addCookie() method on response.

Code Snippet:

 
See full example below:

—index.jsp—

 

—Cookie.java—

 
—cookie.jsp—

 

Explanation:
Once you run the code, you will see a cookie has been created with name “JSESSIONID”. This JSESSIONID is assigned by the apache tomcat server to the client or browser.
Expiration of this JSESSIONID can be configured in web.xml file.
 
cookies1

 
A cookie will be set, when you click on the ‘Cookies’ link. You can give any name to the link, Apple, for example.
This cookie is created using the code above.

 
cookie2