Lab 1
Lab 1
Objectives
• understand the servlet session
• develop a simple client-server application
Servlets come with three scopes that allow you to store data at various levels and for various durations:
• The Context (Application) Scope stores data for all clients as long as the server is running. You
access it using the get/set attribute methods of the ServletContext object (accessible from the
servlet).
• The Session Scope stores data per client as long as the session of the client has not expired. You
access it using the get/set attribute methods of the HttpSession object (accessible
in doGet/Post from request). Read the API of request object to see what else can be done
with it.
• The Request Scope stores data per client as long as the response of the current request has not
been sent yet. You access it using the get/set attribute methods of the
ServletRequest object (accessible in doGet/Post from request).
NOTES:
1. Open Eclipse and create a new dynamic web project named LastName_v2. Choose Tomcat as
the target runtime and select the default configuration.
To create a new dynamic web project, go to File -> New -> Dynamic Web Project.
To choose Tomcat as the target runtime, click on New Runtime... and select Apache
Tomcat from the list. Then browse to the installation directory of Tomcat and click on
Finish.
To select the default configuration, click on Next until you reach the Web Module page.
Then click on Finish.
2. In the src folder of your project, create a new servlet named CalculatorServlet. This
servlet will handle the GET requests and calculate the total price. Write some Java code to
implement the doGet method of the servlet.
Calculate the total price using the formula: 𝑡𝑜𝑡𝑎𝑙 = 𝑛𝑜𝐼𝑡𝑒𝑚𝑠 ∗ 𝑝𝑟𝑖𝑐𝑒 ∗
(1 + 𝑡𝑎𝑥 100).
double total = noItems * price * (1 + tax / 100);
You may need to round the result to two decimal places using methods such as
Math.round or String.format:
total = Math.round(total * 100) / 100.0;
Set the content type of the response object to text/html using the setContentType
method.
response.setContentType("text/html");
Get a print writer from the response object using the getWriter method:
PrintWriter out = response.getWriter();
Write some HTML code to display the total price to the output using the print writer.
You may also include some information about the input values and the calculation
formula:
out.println("<html>");
out.println("<head>");
out.println("<title>Shopping cart Price Calculator</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Shopping cart Price Calculator</h1>");
out.println("<p>You entered:</p>");
out.println("<ul>");
out.println("<li>Number of items: " + noItems + "</li>");
out.println("<li>Price of each item: $" + price + "</li>");
out.println("<li>Tax rate: " + tax + "%</li>");
out.println("</ul>");
out.println("<p>The total price is calculated as:</p>");
out.println("<p>total = noItems * price * (1 + tax / 100)</p>");
out.println("<p>The total price is: $" + total + "</p>");
out.println("</body>");
out.println("</html>");
Here is an example output:
3. In the WEB-INF folder of your project, open the web.xml file. This file contains the
configuration of your web application. Write some XML code to map the servlet class
CalculatorServlet to the URL pattern /CalculatorServlet. This will enable the web
server to invoke the servlet when the form is submitted.
To map a servlet class to a URL pattern, use <servlet> and <servlet-mapping> tags with
subtags such as <servlet-name>, <servlet-class>, and <url-pattern>.
<web-app>
<servlet>
<servlet-name>CalculatorServlet</servlet-name>
<servlet-class>CalculatorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CalculatorServlet</servlet-name>
<url-pattern>/CalculatorServlet</url-pattern>
</servlet-mapping>
</web-app>
In the WEB-INF folder of your project, open the web.xml file. This file contains the
configuration of your web application. Write some XML code to define a context parameter
named defaultTaxRate and assign it a value of 13. This will set a default value for the tax
rate parameter in case it is missing from the request.
To define a context parameter, use a <context-param> tag with subtags such as <param-
name> and <param-value>:
<web-app>
<!-- ... -->
<context-param>
<param-name>defaultTaxRate</param-name>
<param-value>13</param-value>
</context-param>
</web-app>
Modify the CalculatorServlet class in the src folder of your project to:
get the default tax rate value from the ServletContext object using the
getInitParameter method with a key of defaultTaxRate if the tax rate parameter is
missing. Parse this value into a double value and store it in the local variable named tax and
use it for the calculations.
To get the default tax rate value from the ServletContext object, use the
getInitParameter method with "defaultTaxRate" as an argument. This method
returns the value of the context parameter that matches the given name, or null if
there is no such parameter:
String defaultTax =
getServletContext().getInitParameter("defaultTaxRate");
To parse this value into a double value and store it in a local variable named tax, use
methods such as Double.parseDouble with defaultTax as an argument:
Modify the CalculatorServlet class in the src folder of your project to:
1. If the tax rate parameter is not null or empty, parse it into a double value and store it in the
local variable named tax. Also, store this value as an attribute in the HttpSession object using
the setAttribute method with a key of taxRate.
• To get the HttpSession object from the request object, use the getSession
method without any arguments.
HttpSession session = request.getSession();
• To store the tax rate value as an attribute in HttpSession object with a key of
"taxRate", use methods such as setAttribute with "taxRate" and tax as
arguments:
session.setAttribute("taxRate", tax);
• To get the tax rate value after storing it as an attribute in the HttpSession object”
(double) session.getAttribute("taxRate”);
• If there is no attribute named taxRate in the HttpSession object, get the default
tax rate value from the ServletContext object using the getInitParameter
method with a key of defaultTaxRate. Parse this value into a double value and
store it in the local variable named tax and use it for the calculations.
• A sequence of commands to test the HttpSession feature by sending multiple requests with
different or missing tax rate parameters and observing how the servlet uses the stored value
from the session attribute or the default value from the context parameter:
• To be able to use sessions with curl, you need to use –c and –b options with curl. Use –c for the
first curl command to write all cookies after a completed operation. Curl writes all cookies from
its in-memory cookie storage to the given file at the end of operations. If no cookies are known,
no data is written. Then use –b for the next sequences of curl commands to use the session
created. Example:
#first create session.txt file in the directory where you are running
your command.
#For MacOS/Unix-based:
touch session.txt
The first command should return an HTML page that displays the total price as $57.50 and store
the tax rate of 15% in the session attribute. The second command should return an HTML page
that displays the total price as $57.50, using the stored tax rate of 15% from the session
attribute. The third command should return an HTML page that displays the total price as
$60.00 and update the tax rate of 20% in the session attribute.