Java Web App - HttpSession

This is a small example that shows HTTP Sessions in a Java Web App.

This is the structure of my project:



And the code:

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>biz.tugay.myshopcart</groupId>
    <artifactId>shop-cart</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>shop-cart Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>shop-cart</finalName>
    </build>
</project>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
 
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
 
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <page-encoding>UTF-8</page-encoding>
            <scripting-invalid>true</scripting-invalid>
            <include-prelude>/hf/header.jsp</include-prelude>
            <include-coda>/hf/footer.jsp</include-coda>
            <trim-directive-whitespaces>true</trim-directive-whitespaces>
            <default-content-type>text/html</default-content-type>
        </jsp-property-group>
    </jsp-config>
 
</web-app>

index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="/shop" />

header.jsp
<%@ page pageEncoding="utf-8" %>
<%@ page contentType="text/html; utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link href="<c:url value="/resources/css/bootstrap.min.css" />"
          rel="stylesheet" media="screen">
</head>
<body>

footer.jsp
</body>
</html>

browse.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div class="container" style="margin-top: 50px">
    <h1>Product List</h1>
 
    <a href="<c:url value="/shop"><c:param name="action" value="viewCart"/></c:url>">View Cart</a>
 
    <br />
    <a href="
            <c:url value="/shop">
                <c:param name="action" value="addToCart"/>
                <c:param name="productName" value="Tape" />
             </c:url>
             ">
        Tape
    </a>
    <br />
    <a href="
            <c:url value="/shop">
                <c:param name="action" value="addToCart"/>
                <c:param name="productName" value="Paint" />
             </c:url>
             ">
        Paint
    </a>
    <br />
    <a href="
            <c:url value="/shop">
                <c:param name="action" value="addToCart"/>
                <c:param name="productName" value="Glue" />
             </c:url>
             ">
         Glue
    </a>
    <br />
    <a href="
            <c:url value="/shop">
                <c:param name="action" value="addToCart"/>
                <c:param name="productName" value="SandPaper" />
             </c:url>
             ">
        SandPaper
    </a>
    <br />
</div>

viewCart.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div class="container" style="margin-top: 50px">
 
    <h1>Cart</h1>
 
    <a href="<c:url value="/shop" />">
        Back to Product List
    </a>
    <br />
    <br />
 
<%--@elvariable id="products" type="java.util.Map<java.lang.String,java.lang.Integer>"--%>
    <c:forEach items="${sessionScope.products}" var="product">
        <strong>${product.key} </strong> - ${product.value}
        <br />
    </c:forEach>
    <br /><br />
    <a href="
        <c:url value="/shop">
            <c:param name="action" value="emptyCart"/>
        </c:url>">
        Empty Cart
    </a>
</div>

ShopServlet.java
package biz.tugay.myshopcart;
/* User: koray@tugay.biz Date: 24/06/15 Time: 13:11 */
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
@WebServlet(urlPatterns = "/shop")
public class ShopServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
 
        String action = req.getParameter("action");
 
        if (action == null) {
            req.getRequestDispatcher("/browse.jsp").forward(req,resp);
            return;
        }
 
        if (action.equals("addToCart")) {
            String productToAdd = req.getParameter("productName");
            addProductToSession(req.getSession(),productToAdd);
            resp.sendRedirect(getServletContext().getContextPath()+"/shop?action=viewCart");
            return;
        }
 
        if (action.equals("viewCart")) {
            req.getRequestDispatcher("/viewCart.jsp").forward(req,resp);
            return;
        }
 
        if (action.equals("emptyCart")) {
            if (req.getSession().getAttribute("products") != null) {
                req.getSession().setAttribute("products",null);
            }
            resp.sendRedirect(getServletContext().getContextPath()+"/shop");
            return;
        }
 
    }
 
    private void addProductToSession(HttpSession session, String productToAdd) {
 
        @SuppressWarnings("unchecked")
        Map<String, Integer> products = (Map<String, Integer>) session.getAttribute("products");
 
        if (products == null) {
            products = new HashMap<String, Integer>();
        }
 
        if (products.containsKey(productToAdd)) {
            products.put(productToAdd, products.get(productToAdd) + 1);
        } else {
            products.put(productToAdd, 1);
        }
 
        session.setAttribute("products",products);
    }
 
}