Forward Call from a Servlet

This example shows how to forward a http call from a servlet to another page in the same web application.
To do a forward we need to get an instance of RequestDispatcher by calling the getRequestDispatcher() method on the HttpServletRequest object.
The page to which the call will be forwarded is sent to the method as parameter. Finally the forward() method of the RequestDispatcher is called with both the request and response objects as parameters.

Continue reading

Get and Set Session Variables in a Servlet

This code example shows how to set and get variables stored in a session. To get a reference to the session object we call the getSession() method of the HttpServletRequest object.
We send the argument true to the method to tell it to create the session if it doesn’t exist.
Then we try to get the session variable ‘VisitCounter’ from the session by calling the method getAttribute().
It’s supposed to be stored as an Integer object, so we cast it to an Integer directly.
If the parameter is null, we create a new Integer object with the value of one (1) and add it to the session, else we add one to the object retrieved from the session and write it back to the session again. When writing a variable to the session the method setAttribute() is used.
Then we print out the value of the session parameter, which tells how many times this page has been displayed during this particular session.

Continue reading

Get Users IP Address in a Servlet

This code example shows how to obtain the IP address of the user that calls the server.
The Request object has a few neat methods to get information about the call and about the caller, and one of them is named getRemoteAddr() which returns the IP address of the calling computer.
In the example below we print out the IP address on a blank html-page.

Continue reading

Get Request Parameters in a Servlet

This example shows how to get the parameters sent in a http request to a servlet. In this example we use the method service() which will process requests of type GET as well as requests of type POST.
To get the parameter names the method getParameterNames() is called on the request object. The method returns an Enumeration which we use to loop through the parameter names, and for each name the method getParameter() is called on the request object to get the value of that parameter.

Continue reading