m0_69233734 2024-08-04 23:03 采纳率: 61.9%
浏览 18
已结题

为什么点击加入购物车跳转页面应用程序找不到对应的资源该怎么修改

img

img

img

img

img

<----------------------------------------------------------------->

package com.neuedu.myspring.controller;

import org.springframework.web.bind.annotation.*;
import com.neuedu.myspring.entity.Cart;
import com.neuedu.myspring.service.CartService;

@RestController
@RequestMapping("/cart")
public class CartController {

    private final CartService cartService;

    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    @PostMapping("/cart")
    public String addItemToCart(@RequestParam String itemId) {
        Cart cart = new Cart(); // 创建一个新的 Cart 对象
        cart.setItemid(itemId); // 设置商品 ID
        cartService.addItemToCart(cart);
        return "Item added to cart successfully.";
    }
}
<----------------------------------------------------------------->
package com.neuedu.myspring.controller;

import com.neuedu.myspring.dao.ItemMapper;
import com.neuedu.myspring.dao.RecommendMapper;
import com.neuedu.myspring.entity.Item;
import com.neuedu.myspring.entity.Recommend;
import com.neuedu.myspring.entity.User;
import com.neuedu.myspring.itcmcf.CFWrite;
import com.neuedu.myspring.itcmcf.Starter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
public class ItemController {
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RecommendMapper recommendMapper;

    @GetMapping(value = "/items")
    public String selectAll(Model model, HttpSession session) {

        List<Item> items = itemMapper.selectAll();

//        for (Item item : items) {
//            System.out.println(item);
//        }
        // 将数据Model传递给前端页面,用于绑定数据
        model.addAttribute("items",items);
        // 毕设中可以这样使用,生产开发中,不能用,选择空闲时间后台自动调用
        // 调用推荐算法
        Starter.run();
        //读取物品推荐信息
//        List<Recommend> recommends = recommendMapper.selectByUserId("u2730");
        User user = (User)session.getAttribute("user");
        String userId = user.getUid()+"";
        List<Recommend> recommends = recommendMapper.selectByUserId(userId);
//        for(Recommend recommend : recommends) {
//            System.out.println(recommend);
//        }
        model .addAttribute("recommends",recommends);
        //返回页面
        return "items";

    }
    @GetMapping(value = "/item/{itemId}")
    public String selectById(@PathVariable("itemId") String itemId, Model model,HttpSession session) {
        //查询数据库
        Item item = itemMapper.selectByPrimaryKey(itemId);
        System.out.println(item);
        // 将数据Model传递给前端页面,用于绑定数据
        model.addAttribute("item",item);
        // 写入大数据HDFS中,用于物品推荐算法
        User user = (User)session.getAttribute("user");
        String userId = user.getUid()+"";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        CFWrite.write(itemId,userId,"click",formatter.format(date));
        //返回页面
        return "item";

    }

    @GetMapping(value = "/cart/{itemId}")
    public String cart(@PathVariable("itemId") String itemId, Model model,HttpSession session) {
        // 写入大数据HDFS中,用于物品推荐算法
        User user = (User)session.getAttribute("user");
        String userId = user.getUid()+"";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        CFWrite.write(itemId,userId,"cart",formatter.format(date));
        //具体加入购物车,功能暂未实现

        //返回页面
        return "redirect:/cart";

    }
}
<----------------------------------------------------------------->
package com.neuedu.myspring.dao;

import com.neuedu.myspring.entity.Cart;
import org.apache.ibatis.annotations.Param;

public interface CartMapper {
    int deleteByPrimaryKey(String itemid);

    int insert(Cart record);

    int insertSelective(Cart record);

    Cart selectByPrimaryKey(String itemid);

    int updateByPrimaryKeySelective(Cart record);

    int updateByPrimaryKey(Cart record);

    int updateQuantityByItemId(@Param("quantity") Integer quantity, @Param("itemid") String itemid);

}

<----------------------------------------------------------------->
package com.neuedu.myspring.entity;

public class Cart {
    private String itemid;

    private String name;

    private Double price;

    private String remark;

    private String image;

    private String quantity;

    public Cart(String itemid, String name, Double price, String remark, String image, String quantity) {
        this.itemid = itemid;
        this.name = name;
        this.price = price;
        this.remark = remark;
        this.image = image;
        this.quantity = quantity;
    }

    public Cart() {
        super();
    }

    public String getItemid() {
        return itemid;
    }

    public void setItemid(String itemid) {
        this.itemid = itemid == null ? null : itemid.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark == null ? null : remark.trim();
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image == null ? null : image.trim();
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity == null ? null : quantity.trim();
    }
}
<----------------------------------------------------------------->
package com.neuedu.myspring.service;

import com.neuedu.myspring.dao.CartMapper;
import com.neuedu.myspring.entity.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CartService {

    private final CartMapper cartMapper;

    @Autowired
    public CartService(CartMapper cartMapper) {
        this.cartMapper = cartMapper;
    }

    public void addItemToCart(Cart cart) {
        cartMapper.insert(cart);
    }
}
<----------------------------------------------------------------->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.neuedu.myspring.dao.CartMapper">
  <resultMap id="BaseResultMap" type="com.neuedu.myspring.entity.Cart">
    <constructor>
      <idArg column="itemid" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="name" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="price" javaType="java.lang.Double" jdbcType="DOUBLE" />
      <arg column="remark" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="image" javaType="java.lang.String" jdbcType="VARCHAR" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List">
    itemid, name, price, remark, image
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from cart
    where itemid = #{itemid,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from cart
    where itemid = #{itemid,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.neuedu.myspring.entity.Cart">
    insert into cart (itemid, name, price, 
      remark, image)
    values (#{itemid,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=DOUBLE}, 
      #{remark,jdbcType=VARCHAR}, #{image,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.neuedu.myspring.entity.Cart">
    insert into cart
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="itemid != null">
        itemid,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="price != null">
        price,
      </if>
      <if test="remark != null">
        remark,
      </if>
      <if test="image != null">
        image,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="itemid != null">
        #{itemid,jdbcType=VARCHAR},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="price != null">
        #{price,jdbcType=DOUBLE},
      </if>
      <if test="remark != null">
        #{remark,jdbcType=VARCHAR},
      </if>
      <if test="image != null">
        #{image,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.neuedu.myspring.entity.Cart">
    update cart
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="price != null">
        price = #{price,jdbcType=DOUBLE},
      </if>
      <if test="remark != null">
        remark = #{remark,jdbcType=VARCHAR},
      </if>
      <if test="image != null">
        image = #{image,jdbcType=VARCHAR},
      </if>
    </set>
    where itemid = #{itemid,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.neuedu.myspring.entity.Cart">
    update cart
    set name = #{name,jdbcType=VARCHAR},
      price = #{price,jdbcType=DOUBLE},
      remark = #{remark,jdbcType=VARCHAR},
      image = #{image,jdbcType=VARCHAR}
    where itemid = #{itemid,jdbcType=VARCHAR}
  </update>
</mapper>
<----------------------------------------------------------------->
<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>所有商品信息</title>


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function addToCart(itemId) {
            $.ajax({
                url: '/cart' + itemId,
                type: 'POST',
                success: function (data) {
                    alert('Item added to cart successfully.');
                },
                error: function (error) {
                    alert('Failed to add item to cart.');
                }
            });
        }
    </script>


    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .main {
            width: 1098px;
            margin: 0 auto;
            text-align: center;

        }
        table{
            width: 100%;
            border-collapse: collapse;
        }
        th,td{
            border: 1px solid #333;
        }
        table img{
            width: 100px;
            height: 100px;
        }
    </style>
</head>
<body>
<div class="main">
    <h1>所有商品信息</h1>
    <table>
        <tr>
            <th>物品编号</th>
            <th>物品名称</th>
            <th>价格</th>
            <th>描述</th>
            <th>图片</th>
            <th>操作</th>
        </tr>
        <tr th:each="item:${items}">
            <td th:text="${item.itemid}"></td>
            <td th:text="${item.name}"></td>
            <td th:text="${item.price}"></td>
            <td th:text="${item.remark}"></td>
            <td><img th:src="${item.image}"></td>
            <td><a th:href="@{/item/{itemId}(itemId=${item.itemid})}">显示详情</a>|
                <a th:onclick="addToCart(${item.itemid})" th:href="@{/cart/{itemId}(itemId=${item.itemid})}">加入购物车</a>|
                <a href="">添加物品</a>|<a href="">修改商品</a>|<a href="">删除物品</a></td>
        </tr>
    </table>
    <h1>推荐商品信息</h1>
    <table>
        <tr>
            <th>用户编号</th>
            <th>物品编号</th>
            <th>推荐值</th>
        </tr>
        <tr th:each="r:${recommends}">
            <td th:text="${r.userid}"></td>
            <td th:text="${r.itemid}"></td>
            <td th:text="${r.cfvalue}"></td>
        </tr>
    </table>
</div>
</body>
</html>
<----------------------------------------------------------------->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>购物车信息</title>
</head>
<body>
<div class="main">
    <h1>购物车信息</h1>
    <table>
        <tr>
            <th>物品编号</th>
            <th>物品名称</th>
            <th>价格</th>
            <th>描述</th>
            <th>图片</th>
            <th>操作</th>
        </tr>
        <tr th:each="item:${items}">
            <td th:text="${item.itemid}"></td>
            <td th:text="${item.name}"></td>
            <td th:text="${item.price}"></td>
            <td th:text="${item.remark}"></td>
            <td><img th:src="${item.image}"></td>
    </table>
</div>
<a href="/items">返回</a>

</body>
</html>

<----------------------------------------------------------------->

为什么点击加入购物车跳转页面应用程序找不到对应的资源该怎么修改

  • 写回答

22条回答 默认 最新

  • 专家-郭老师 Java领域新星创作者 2024-08-04 23:04
    关注
    获得0.45元问题酬金

    🕗晚上好,题主!目前:🟢[在线]
    📢参考通义千问、由郭老师整理提供!
    📣今日诗号:七弦抚尽,何处觅知音,但向朗月空林。翰墨残迹,谁得千秋理,且听松涛竹意。

    您遇到的问题是点击“加入购物车”按钮后,页面跳转失败,提示“应用程序找不到对应的资源”。这是因为您的代码中存在以下问题:

    1. 前端JS代码错误:

      • url: '/cart' + itemId, 这行代码有误,应该是 /cart/ + itemId,漏掉了/
      • type: 'POST', 应该改为 type: 'GET', 因为您后台 CartController 使用的是 @GetMapping("/cart/{itemId}") 来处理请求。
    2. 前端页面跳转逻辑错误:

      • items.html 中, addToCart 函数中使用了 th:hrefth:onclick 同时绑定事件,这会导致请求发送两次。
      • 您需要删除 th:href="@{/cart/{itemId}(itemId=${item.itemid})}", 只保留 th:onclick
    3. 缺少购物车页面逻辑:

      • 您只提供了一个空的购物车页面 cart.html,没有编写从后端获取购物车数据并在页面展示的逻辑。

    以下是修改后的代码:

    1. 前端 items.html 修改:

    <!DOCTYPE html>
    <html lang="en"  xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>所有商品信息</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            function addToCart(itemId) {
                $.ajax({
                    url: '/cart/' + itemId,  // 修改1:添加了 /
                    type: 'GET',              // 修改2:改为 GET 请求
                    success: function (data) {
                        alert('Item added to cart successfully.');
                        window.location.href = '/cart'; // 添加跳转到购物车页面
                    },
                    error: function (error) {
                        alert('Failed to add item to cart.');
                    }
                });
            }
        </script>
        <style>
            /* ... css 代码 ... */ 
        </style>
    </head>
    <body>
    <div class="main">
        <h1>所有商品信息</h1>
        <table>
            <thead>
            <tr>
                <th>物品编号</th>
                <th>物品名称</th>
                <th>价格</th>
                <th>描述</th>
                <th>图片</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item:${items}">
                <td th:text="${item.itemid}"></td>
                <td th:text="${item.name}"></td>
                <td th:text="${item.price}"></td>
                <td th:text="${item.remark}"></td>
                <td><img th:src="${item.image}"></td>
                <td>
                    <a th:href="@{/item/{itemId}(itemId=${item.itemid})}">显示详情</a>|
                    <a th:onclick="addToCart(${item.itemid})">加入购物车</a> |
                    <a href="">添加物品</a>|<a href="">修改商品</a>|<a href="">删除物品</a>
                </td>
            </tr>
            </tbody>
        </table>
        <h1>推荐商品信息</h1>
        <table>
            <thead>
            <tr>
                <th>用户编号</th>
                <th>物品编号</th>
                <th>推荐值</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="r:${recommends}">
                <td th:text="${r.userid}"></td>
                <td th:text="${r.itemid}"></td>
                <td th:text="${r.cfvalue}"></td>
            </tr>
            </tbody>
        </table>
    </div>
    </body>
    </html>
    

    2. 后端 CartController 修改:

    package com.neuedu.myspring.controller;
    
    import org.springframework.web.bind.annotation.*;
    import com.neuedu.myspring.entity.Cart;
    import com.neuedu.myspring.service.CartService;
    import javax.servlet.http.HttpSession;
    
    @RestController
    @RequestMapping("/cart")
    public class CartController {
        private final CartService cartService;
    
        public CartController(CartService cartService) {
            this.cartService = cartService;
        }
    
        @GetMapping("/{itemId}") // 修改为 GetMapping
        public String addItemToCart(@PathVariable String itemId, HttpSession session) {
            // 获取用户信息
            // ...
    
            Cart cart = new Cart(); 
            cart.setItemid(itemId); 
            // 设置其他属性,例如从数据库中查询商品信息
            // ... 
    
            cartService.addItemToCart(cart);
            return "Item added to cart successfully.";
        }
    }
    

    3. 完善购物车页面 cart.html 逻辑:

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>购物车信息</title>
    </head>
    <body>
    <div class="main">
        <h1>购物车信息</h1>
        <table>
            <thead>
            <tr>
                <th>物品编号</th>
                <th>物品名称</th>
                <th>价格</th>
                <th>描述</th>
                <th>图片</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item : ${cartItems}"> <div> 这里需要获取后端购物车数据 </div>
                <td th:text="${item.itemid}"></td>
                <td th:text="${item.name}"></td>
                <td th:text="${item.price}"></td>
                <td th:text="${item.remark}"></td>
                <td><img th:src="${item.image}"></td>
            </tr>
            </tbody>
        </table>
    </div>
    <a href="/items">返回</a>
    </body>
    </html>
    

    4. 实现 CartService 中获取购物车数据的方法:

    您需要在 CartService 中添加一个方法,用于从数据库或Session中获取购物车数据,并在 CartController 中调用该方法,将数据传递给 cart.html 页面。

    总结:

    • 修改前端JS代码,修正url和请求方式。
    • 修改前端页面跳转逻辑,避免重复请求。
    • 完善购物车页面逻辑,从后端获取数据并展示。

    完成以上修改后,您的“加入购物车”功能应该就可以正常工作了。

    评论

报告相同问题?

问题事件

  • 系统已结题 8月12日
  • 创建了问题 8月4日

悬赏问题

  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等
  • ¥15 联想交换机NE2580O/NE1064TO安装SONIC