Http Session
package com.example.demo;
public class Cart {
private String name;
private int quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
package com.example.demo;
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.io.PrintWriter;
@WebServlet(name = "FirstServlet", urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
HttpSession session = req.getSession();
Cart cart = (Cart) session.getAttribute("cart");
String name = req.getParameter("name");
int quantity = Integer.parseInt(req.getParameter("quantity"));
if (cart == null) {
cart = new Cart();
}
cart.setName(name);
cart.setQuantity(quantity);
session.setAttribute("cart", cart);
req.getRequestDispatcher("cart.jsp").forward(req, resp);
}
}<%@ page import="com.example.demo.Cart" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Cart cart = (Cart) session.getAttribute("cart");
%>
<%=cart.getName() + " " + cart.getQuantity()%>
</body>
</html>
Комментарии
Отправить комментарий