How To Set up Cookies With Servlet

Talk is cheap. Show me the code. ~ Linus Torvalds

A browser cookie is a small piece of data sent from website and stored in user’s web browser while the user is browsing a given website. Every time user loads the website, browser sends the cookie back to the server to notify the website of the user’s previous activity.

We are going to learn how to set up cookies with servlet. We are going to create three files:

  • HelloForm.java (servlet).
  • HelloForm.html
  • ReadCookie.java (servlet).

Creating the first Servlet which is HelloForm.java, here is the code:

Servlet 1

Creating HelloForm.html here is the code

html

Now I want you to run HelloForm.html on your server and you will get something like this:

output

Now I need you to enter First Name and Last Name. After that, click submit. Now we need a way to read the stored names. I am going to use First Name as Henry and Last Name as Mbugua. Lastly, we will create Servlet to read our names.

Creating ReadCookie.java, here is the code:

readcookie

Now we will run ReadCookie.java in our server and see if we can read our stored names. Here is my result:

result

Have something to add, leave me a comment. Happy coding!

Advertisements

One thought on “How To Set up Cookies With Servlet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s