Отправка информации между двумя страницами JSP через сервлет - PullRequest
0 голосов
/ 28 октября 2019

Это для проекта в классе. Я работаю с Spring Tool Suite 3.9.9 У меня есть 2 страницы JSP. На первом я отображаю продукты, содержащиеся в карте (она имитирует базу данных). Вторая страница JSP - это корзина для покупок. Моя цель - добавить товар на страницу корзины покупок.

На странице товаров, когда я нажимаю кнопку «добавить в корзину», я должен быть перенаправлен на страницу корзины покупок, и на ней должен отображаться товар. выбрал на этой странице. На странице корзины покупок отображаются данные с карты.

I Отображается только часть кода для каждой страницы, поскольку она длинная.

  • код страницы jspпродукты

                                                    <<form action="shoppingcard.jsp" method="get">
                                                    <p> <%= ptp.getId() %> </p>
                                                    <%Object product=ptp;
                                                    request.setAttribute("purchase", ptp); %>
                                                    <input type="submit" value="add to cart">
                                                    <button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Add to Cart</button>
                                                    </form>
                                                </div>

страница для корзины покупок

ProductStore products = new ProductStore();
                Map<String,ProductBean> prodList = products.getProducts();

                ShoppingcardStore db = new ShoppingcardStore();
                Map<String,ProductBean> list = db.getShoppingcard();

                Object purchased = request.getAttribute("purchase");
                if(purchased!=null){
                    out.println("<h1>Ok</h1>");
                    ProductBean x = (ProductBean) purchased;
                    db.Purchase(x);
                    // TODO display confirmation that the product has been added properly to the wish list.
                }%>
                <!-- Product Slick -->
                <div class="col-md-9 col-sm-6 col-xs-6">
                    <div class="row">
                        <div id="product-slick-1" class="product-slick">
                <%  if(list != null){
                    Object[] Shoppingcardlist = list.values().toArray();
                    ProductBean ptp;
                    for(int i = 0; i<Shoppingcardlist.length; i++){
                        ptp = (ProductBean)Shoppingcardlist[i];
                        // TODO display the info of the current wish list.
                %>

                            <!-- Product Single -->
                            <div class="product product-single">


Я также покажу вам страницы Java, где хранятся продукты и на всякий случай создается класс productbean.

package javaPackage;

import java.util.HashMap;
import java.util.Map;

public class ShoppingcardStore {
private static Map<String,ProductBean> ShoppingcardMap = new HashMap<>();

    static {
        ShoppingcardMap.put("1", new ProductBean("1", "Shirt", "15","clothing", "shirt", "nike", "M", "M", "khdfbd", "Camelot", "cotton", "summer", 15, "./img/product01.jpg", "./img/thumb-product01.jpg" ,"./img/main-product01.jpg"));
        ShoppingcardMap.put("2", new ProductBean("2", "Shirt", "11","clothing", "shirt", "adidas", "M", "W", "khdfbd", "Camelot", "cotton", "summer", 30, "./img/product02.jpg", "./img/thumb-product02.jpg" ,"./img/main-product02.jpg"));
        ShoppingcardMap.put("3", new ProductBean("3", "Shoes", "15","shoes", "boots", "liu-jo", "42", "W", "khdfbd", "white", "leather", "summer", 10, "./img/product03.jpg", "./img/thumb-product03.jpg" ,"./img/main-product03.jpg"));
    }
    public ShoppingcardStore() {

    }
    public Map<String,ProductBean> getShoppingcard() {
        return ShoppingcardMap;
    }
    public ProductBean getInfo(String id) {
        return (ProductBean) ShoppingcardMap.get("id");
    }
    public void Purchase(ProductBean p) {
        ShoppingcardMap.put(p.getId(),p);
    }
}

Страница, на которой я храню товары в корзине, очень похожа на предыдущую, поэтому я не буду отображать ее. Наконец, класс, в котором я создаю объект productbean

import java.time.LocalDate;
import java.util.*;
public class ProductBean implements Comparable{
    //Holds the identifier of the product
    private String id;
    //Holds the name of the product
    private String name;
    //Holds the price of the product
    private String price;
    //Holds the category of the product (clothing, shoes, etc)
    private String category;
    //Holds the type of the product (shoes: sneakers, running, boots etc)
    private String type;
    //Holds the brand
    private String brand;
    //Size of the product (depends on the product)
    private String size;
    //Men = M, Women = F, Kids = K
    private String gender;
    //date of the listing
    private LocalDate date;
    //description of the product
    private String description;
    //main colour of the product
    private String colour;
    //materials of the product
    private String material;
    //winter, summer etc
    private String collection;
    //percentage of discount
    private int sale;

    // the path to the image
    private ArrayList<String> mainImage;

    private ArrayList<String> thumbImage;

    private ArrayList<String> image;


    // the rating of the product (1 to 5 stars)
    private int rating;
    // amount of users that have rated the product
    private int rateNum;

    private ArrayList<String[]> reviews;

    //Create a new Product
    public ProductBean() {
    }

    public ProductBean(String id, String name, String price, String category, String type ,String brand, 
                        String size, String gender, String description, String colour, String material,
                        String collection, int sale, String image, String thumb, String mainImage) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.category = category;
        this.type = type;
        this.brand = brand;
        this.size = size;
        this.gender = gender;
        this.date = LocalDate.now();
        this.description = description;
        this.colour = colour;
        this.material = material;
        this.collection = collection;
        this.sale = sale;
        this.image = new ArrayList<>();
        this.thumbImage = new ArrayList<>();
        this.mainImage = new ArrayList<>();
        this.image.add(image);
        this.thumbImage.add(thumb);
        this.mainImage.add(mainImage);
        this.rating = 0;
        this.reviews = new ArrayList<>();
    }
    public String getId() {
        return id;
    }

Iтакже есть функции в этом классе, но они действительно просты, они просто делают то же самое, что и "getId" для атрибутов других, и они не являются проблемой, поэтому нет необходимости отображать их, я думаю

На момент, когда я нажимаюна кнопке меня перенаправляют на страницу корзины покупок, но у меня даже нет строки «ок», которая напечатана, что означает, что стоимость купленного товара равна «нулю». Если я использую Session.getattribute и устанавливаю атрибут вместо запроса, я вижу напечатанную строку «Ok», но продукт не появляется на странице. У меня есть некоторые подсказки, но я не знаю, как это сделать: мой профессор сказал мне использовать идентификатор продукта и отправить его сервлету, а затем на вторую страницу JSP. Я покажу вам контрольный сервлет, если у вас есть идея, что мне с ним делать

public class ControllerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // Hash table of RequestHandler instances, keyed by request URL
    private Map handlerHash = new HashMap();

    // Initialize mappings: not implemented here

    public void init(ServletConfig config) throws ServletException {
        // all HTML pages
        handlerHash.put("/index.html", new javaPackage.ShowRecordRequestHandler());
        handlerHash.put("/blank.html", new javaPackage.ShowRecordRequestHandler());
        handlerHash.put("/checkout.html", new javaPackage.ShowRecordRequestHandler());
        handlerHash.put("/products.html", new javaPackage.ShowRecordRequestHandler());
        handlerHash.put("/product-page.html", new javaPackage.ShowRecordRequestHandler());
        // handlerHash.put("/login.html", new javaPackage.ShowRecordRequestHandler());
        handlerHash.put("/profile.html", new userAccount.ManageProfile());
        handlerHash.put("/shoppingcard.html",new javaPackage.ShowRecordRequestHandler());
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String sPath = request.getServletPath();
        // Retrieve from the HashMap the instance of the class which implements the logic of the requested URL
        Object objAux = handlerHash.get(sPath);

        // If no instance is retrieved redirects to error
        if (objAux == null) {
            request.getRequestDispatcher("error.html").forward(request, response);
            return;
        } else {
            // Call the method handleRequest of the instance in order to obtain the URL
            RequestHandler rh = (RequestHandler) objAux;
            String sView = rh.handleRequest(request, response);

            // Dispatch the request to the URL obtained
            request.getRequestDispatcher(sView).forward(request, response);
            return;
        }
    }
}
...