京东网站代码实现

创建数据库表

    1.用户表(头像 path)(id  username password path)

    2.商品表(rid rname price img)

    3.个人信息表(gid uid(关联用户表) name sex birthday)

    4.购物车表(cid sid uid(关联用户表) cname price num img color version method )

 

   

后端代码

  1.创建SpringBoot项目(一个javaweb的开发框架,和SpringMVC类似,对比其他javaweb框架的好处,官方说是简化开发,约定大于配置, you can “just run”,能迅速的开发web应用,几行代码开发一个http接口)

  2.配置文件(application.properties)

  3.导入相关依赖()

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>JD</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>JD</name>
    <description>JD</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
<!--    连接数据库驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
<!--       Thymeleaf模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--        Web驱动-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        测试库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<!--        注解插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
<!--    Mybatis依赖连接数据库-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
<!--    数据库连接池druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.11</version>
        </dependency>

<!--        整合分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.2</version>
        </dependency>


        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.46</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.3</version>
            </plugin>
        </plugins>
    </build>
</project>

 

  4.编写实体类(用户实体类 商品实体类 个人信息实体类 购物车实体类)

  5.编写三层实现 登录 注册 查询 修改  添加 删除

前端代码

  1.自行编写按照京东模型写

逻辑:

  导入js配置 连接数据库配置文件(application.properties) 以及 相关依赖

 

 

 

 

编写用户表 商品表 购物车表 个人信息表 实体类(可以使用Data注解替换get set )

 

 

 

编码dao层实现前后交互(可在后端实现sql语句)写sql语句要加上注解表示要干什么

UserDao接口

package com.example.jd.Dao;

import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 用户实体类
 */
@Mapper // 声明接口
public interface UserDao {

    /**
     *根据用户名和密码查询的方法
     */
    @Select("select * from user where username = #{username} and password = #{password}")
    User findByUsernameAndPassword(@Param("username") String username,@Param("password") String password);

    /**
     * 用户保存添加
     *
     */
    @Insert("insert into user(username,password) values(#{username},#{password})")
    boolean increased(User user);


    /**
     *  根据用户查询头像
     */
    @Select("SELECT * FROM `user` WHERE id = #{id}")
    User findByIds(Integer id);

    /**
     * 查询总记录数
     * @return
     */
    @Select("SELECT COUNT(*) FROM commodity")
    Integer findTotalCont();

    /**
     * 分页查询每页记录
     * @param start
     * @param rows
     * @return
     */
    @Select("SELECT * FROM commodity LIMIT #{currentPage},#{rows}")
    List<Commodity> findByPage(int start, int rows);
}

PersonalDao接口

package com.example.jd.Dao;

import com.example.jd.Entity.Personal;
import com.example.jd.Entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface PersonalDao {

    /**
     *  查询回显
     */
    @Select("SELECT * FROM personal WHERE uid = #{uid}")
    Personal findById(Integer uid);

    /**
     * 添加个人信息
     */
    @Insert("INSERT INTO personal(uid) VALUES(#{uid})")
    boolean findByinsert(Personal personal);


    /**
     * 修改个人信息
     */
    @Update("UPDATE personal SET name = #{name}, sex = #{sex} where uid=#{uid};")
    boolean findBypersonal(Personal personal);


    /**
     * 修改头像
     */
    @Update("UPDATE user SET path = #{path} WHERE id = #{id}")
    boolean findByupdates(User user);



}

CommodityDao接口

package com.example.jd.Dao;

import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
@Mapper // 声明接口
public interface CommodityDao {
    /**
     *  查询数据库商品信息
     */
    @Select("SELECT * FROM commodity")
    List<Commodity> findAll();

    /**
     *  根据id查询商品
     */
    @Select("select * from commodity where rid = #{rid}")
    Commodity findById(Integer id);

    /**
     * 根据用户名查询用户信息
     */
    @Select("select * from commodity where rname = #{rname}")
    Commodity findByrname(String rname);


}

CartDao接口

package com.example.jd.Dao;

import com.example.jd.Entity.Cart;
import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface CartDao {

    /**
     *  购物车添加
     */
    @Insert("insert into cart(sid,uid,cname,price,num,img,color,version,method) values(#{sid},#{uid},#{cname},#{price},#{num},#{img},#{color},#{version},#{method})")
    boolean increasedp(Cart cart);

    /**
     * 查询购物车id
     */
    @Select("select * from cart where cid = #{cid}")
    Cart findByIdcart(Integer id);

    /**
     *  根据用户查询id
     */
    @Select("SELECT * FROM cart WHERE uid = #{uid}")
    List<Cart> findAllcart(Integer id);

    /**
     * 购物车 模糊查询
     */
    @Select("SELECT * FROM cart WHERE cname LIKE CONCAT('%',#{cname},'%')")
    List<Cart> findAllfuzzy(String cname);
}

 

 实现service层业务操作

UserService接口

package com.example.jd.service;


import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.PageBean;
import com.example.jd.Entity.User;
import com.github.pagehelper.PageInfo;

import java.util.List;

public interface UserService {

    /**
     * 登录方法
     * @param
     * @return
     */
    User login(String username,String password);

    /**
     * 注册方法
     */
    boolean increased(User user);

    /**
     * 根据用户查询头像
     * @param id
     * @return
     */
    User findByIds(Integer id);

    /**
     * 插件实现分页
     */
     PageInfo<Commodity> qu(int pageNum, int pageSize);

    /**
     * 分页查询
     * @param currentPage
     * @return
     */
    PageBean<Commodity> findUserByPage(Integer currentPage, Integer pageSize);
}

PersonalService接口

package com.example.jd.service;


import com.example.jd.Entity.Personal;
import com.example.jd.Entity.Resp;
import com.example.jd.Entity.User;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

public interface PersonalService {

    /**
     *  查询
     */
    Personal findById(Integer uid);

    /**
     * 添加
     */
    boolean findByinsert(Personal personal);


    /**
     * 修改个人信息
     * @param personal
     * @return
     */
    boolean findBypersonal(Personal personal);

    /**
     * 封账IO流 上传个人头像
     * @param file
     * @return
     */
    Resp<String> updateImg(MultipartFile file, HttpServletRequest request);

    /**
     * 修改头像
     */
    boolean findByupdates(User user);
}

CommodityService接口

package com.example.jd.service;

import com.example.jd.Entity.Commodity;

import java.util.List;

public interface CommodityService {

    /**
     * 查询方法
     */
    List<Commodity> findAll();

    /**
     * 查询指定id
     * @param id
     * @return
     */
    Commodity findById(Integer id);
}

CartService接口

package com.example.jd.service;


import com.example.jd.Entity.Cart;
import com.example.jd.Entity.Commodity;

import java.util.List;

public interface CartService {


    /**
     * 查询购物车id
     */
    Cart findByIdcart(Integer cid);

    /**
     * 添加 购物车
     * @param cart
     * @return
     */
    boolean increasedp(Cart cart);


    /**
     * 根据用户id查询用户购物车
     * @param id
     * @return
     */
    List<Cart> findAllcart(Integer id);

    /**
     * 模糊查询
     */
    List<Cart> findAllfuzzy(String cname);

}

实现类 引入dao层实现业务操作

UserServiceImpl实现类

package com.example.jd.service.impl;

import com.example.jd.Dao.CommodityDao;
import com.example.jd.Dao.UserDao;
import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.PageBean;
import com.example.jd.Entity.User;
import com.example.jd.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    /**
     * 实例化
     */
    @Autowired
    private UserDao userDao;

    @Autowired
    private CommodityDao commodityDao;

    /**
     * 根据用户名和密码查询方法
     * @param
     * @return
     */
    @Override
    public User login(String username,String password) {
            return userDao.findByUsernameAndPassword(username,password);
    }

    /**
     *
     * 注册
     */
    @Override
    public boolean increased(User user) {
        return userDao.increased(user);
    }

    /**
     * 头像回显
     * @param id
     * @return
     */
    @Override
    public User findByIds(Integer id) {
        return userDao.findByIds(id);
    }

    /**
     * 插件查询个人信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Commodity> qu(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Commodity> stud = commodityDao.findAll();
        PageInfo<Commodity> pageInfo = new PageInfo<>(stud);
        return pageInfo;
    }

    /**
     *  分页查询
     */
    @Override
    public PageBean<Commodity> findUserByPage(Integer currentPage, Integer pageSize) {

        PageBean<Commodity> bean = new PageBean<>();

        //获取当前页码
        bean.setCurrentPage(currentPage);

        //设置每页显示的条数
        bean.setRows(pageSize);

        //设置记录数
        Integer seltotle = userDao.findTotalCont();
        bean.setTotalCount(seltotle);

        //当前页显示的数据集合
        int start = (currentPage - 1) * pageSize;
        List<Commodity> comm = userDao.findByPage(start, pageSize);
        bean.setList(comm);

        //设置总页数
        int totalPage = 0;
        if (seltotle % pageSize == 0){
            totalPage = seltotle / pageSize;
        }else {
            totalPage = (seltotle / pageSize) + 1;
        }
        bean.setTotalPage(totalPage);
        System.out.println(totalPage);

        return bean;
    }

}

PersonalServiceImpl实现类

package com.example.jd.service.impl;

import com.example.jd.Dao.PersonalDao;
import com.example.jd.Entity.Personal;
import com.example.jd.Entity.Resp;
import com.example.jd.Entity.User;
import com.example.jd.service.PersonalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Service
public class PersonalServiceImpl implements PersonalService {

    @Autowired
    private PersonalDao personalDao;


    /**
     * 回显个人信息
     * @param uid
     * @return
     */
    @Override
    public Personal findById(Integer uid) {
        return personalDao.findById(uid);
    }

    /**
     *
     * @param personal
     * @return
     */
    @Override
    public boolean findByinsert(Personal personal) {
        return personalDao.findByinsert(personal);
    }

    /**
     * 修改个人信息
     * @param personal
     * @return
     */
    @Override
    public boolean findBypersonal(Personal personal) {
        return personalDao.findBypersonal(personal);
    }


    /**
     * 修改头像
     * @param user
     * @return
     */
    @Override
    public boolean findByupdates(User user) {
        return personalDao.findByupdates(user);
    }

    /**
     * IO流 上传头像
     * @param file
     * @return
     */
    @Override
    public Resp<String> updateImg(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()){
            return Resp.fail("400","文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        String fileName=System.currentTimeMillis()+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        String filepath="D:\\file\\";
        File dest = new File(filepath+fileName);
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        }catch (Exception e){
            e.printStackTrace();
            return Resp.fail("500",originalFilename+"上传失败!");
        }
        User per = new User();
        String s = String.valueOf(dest);
        String[] split = s.split(":");
        s=split[1];
        s = s.replaceAll("\\\\","/");

        Integer uid = (Integer) request.getSession().getAttribute("uid");
        per.setId(uid);

        per.setPath(s);

        personalDao.findByupdates(per);

        return Resp.success(fileName);
    }
}

CommodityServiceImpl实现类

package com.example.jd.service.impl;

import com.example.jd.Dao.CommodityDao;
import com.example.jd.Entity.Commodity;
import com.example.jd.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CommodityServiceImpl  implements CommodityService {
    @Autowired
    private CommodityDao commodityDao;

    /**
     *  查询商品信息
     * @return
     */
    @Override
    public List<Commodity> findAll() {
        return commodityDao.findAll();
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */

    @Override
    public Commodity findById(Integer id) {
        return  commodityDao.findById(id);
    }


}

CartServiceImpl实现类

package com.example.jd.service.impl;

import com.example.jd.Dao.CartDao;
import com.example.jd.Entity.Cart;
import com.example.jd.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartDao cartDao;


    @Override
    public Cart findByIdcart(Integer cid) {
        return cartDao.findByIdcart(cid);
    }

    /**
     * 添加 购物车
     */
    @Override
    public boolean increasedp(Cart cart) {
        return cartDao.increasedp(cart);
    }

    /**
     * 根据用户id查询用户购物车
     * @param id
     * @return
     */
    @Override
    public List<Cart> findAllcart(Integer id) {
        return cartDao.findAllcart(id);
    }

    /**
     * 模糊查询
     * @param cname
     * @return
     */
    @Override
    public List<Cart> findAllfuzzy(String cname) {
        return cartDao.findAllfuzzy(cname);
    }


}

 

实现Controller控制层用于控制前端传递过来数据实现后端操作

UserController

package com.example.jd.Controller;

import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.PageBean;
import com.example.jd.Entity.Personal;
import com.example.jd.Entity.User;
import com.example.jd.service.CommodityService;
import com.example.jd.service.PersonalService;
import com.example.jd.service.UserService;
import com.example.jd.utils.HttpServletRequestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求与响应
 */
@Controller// 声明控制类 处理http请求
public class UserController {


    @Autowired// 实体化
    private UserService userService;

    @Autowired
    private PersonalService personalService;

    @Autowired
    private CommodityService commodityService;

    /**
     * 首页
     * @return
     */
    @GetMapping("/index1")
    public String Index(){
        return "/index";
    }

    /**
     * 登录
     * @return
     */
    @GetMapping("/login1")
    public String login(){
        return "/login";
    }

    /**
     * 注册
     * @return
     */
    @GetMapping("/register1")
    public String register(){
        return "/register";
    }


    /**
     * 登录前后交互请求相应
     * @param request
     * @return
     */
    @PostMapping("/logins")
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request) {
        //1.创建集合存储数据并返回给前端
        HashMap<String, Object> map = new HashMap<>();
        //获取用户名以及密码
        String username = HttpServletRequestUtil.getString(request, "username");
        String password = HttpServletRequestUtil.getString(request, "password");
        //判断是否为空
        if (username != null && password != null) {
            //查询
            User byUsernameAndPassword = userService.login(username, password);
            //判断用户密码是否存在
            if (byUsernameAndPassword != null) {
                //存入session中 (便于后面回显)
                request.getSession().setAttribute("user",byUsernameAndPassword);
                request.getSession().setAttribute("uid",byUsernameAndPassword.getId());


                map.put("success",true);
                //request.getSession().setAttribute("uid",byUsernameAndPassword);
            }else {
                map.put("success",false);
                map.put("Msg","不正确");
            }

        }else {
            map.put("success", false);
            map.put("Msg", "账号密码不可为空");
        }
        return map;
    }

    /**
     *  注册
     *
     */
    @PostMapping("/registerAccount")
    @ResponseBody
    public Map<String,Object> increassed(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        //获取用户名以及密码
        String username = HttpServletRequestUtil.getString(request, "username");
        String password = HttpServletRequestUtil.getString(request, "password");
        //判断是否为空
        if (username != null && password != null){
            //查询数据库中是否有
            User login = userService.login(username, password);
            //判断是否有相同数据
            if (login != null){
                map.put("success", false);
                map.put("Msg", "已有账号");
            }else {
                //注册
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                boolean increased = userService.increased(user);
                map.put("success", increased);

                // 个人信息添加()
                User login1 = userService.login(username, password);
                Personal personal = new Personal();
                personal.setUid(login1.getId());
                personalService.findByinsert(personal);
            }
        }else {
            map.put("success", false);
            map.put("Msg", "不能为空");
        }
        return map;
    }


    /**
     *  登录回显
     */
    @GetMapping("/findOne")
    @ResponseBody
    public Map<String,Object> findOne(HttpServletRequest request){
        //获取用户信息
        User user = (User) request.getSession().getAttribute("user");
        HashMap<String, Object> map = new HashMap<>();
        //头像回显 (只要id)
        User byIds = userService.findByIds(user.getId());
        map.put("byIds",byIds.getPath());
        //名称回显(只要username)
        map.put("one", user.getUsername());
        return map;
    }

    /**
     *  分页查询全部
     */
    @GetMapping("/selectAllPageQuery")
    @ResponseBody
    public PageInfo<Commodity> selectAkllPageQuery(@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize){
        return userService.qu(pageNum,pageSize);
    }


    /**
     * 分页查询全部数据
     */
    @RequestMapping("/getAllPerson")
    @ResponseBody
    public String getAllPerson(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,8);
        //查询全部
        List<Commodity> list = commodityService.findAll();
        //插件实现
        PageInfo<Commodity> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "index";
    }

    /**
     * 分页
     */
    @GetMapping("/getAll")
    @ResponseBody
    public Map<String,Object> getAll(Integer currentPage,Integer pageSize){
        HashMap<String, Object> map = new HashMap<>();
        //查询分页  当前页码  每页显示的条数
        PageBean<Commodity> pageBean = userService.findUserByPage(currentPage, pageSize);
        map.put("pageBean",pageBean);
        return map;
    }


}

PersonalController

package com.example.jd.Controller;

import com.example.jd.Entity.Personal;
import com.example.jd.Entity.Resp;
import com.example.jd.Entity.User;
import com.example.jd.service.PersonalService;
import com.example.jd.utils.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PersonalController {


    @Autowired
    private PersonalService personalService;

    /**
     *  个人信息
     * @return
     */
    @GetMapping("/personal1")
    public String personal(){
        return "/personal";
    }

    /**
     *  修改头像
     */
    @GetMapping("/portrait1")
    public String findByupdate(){
        return "/portrait";
    }


    /**
     * 后端 个人信息修改
     */
    @GetMapping("/findones")
    @ResponseBody
    public Map<String,Object> personals(HttpServletRequest request) throws ParseException {
        HashMap<String, Object> map = new HashMap<>();
        //获取数据
        Integer uid = (Integer) request.getSession().getAttribute("uid");

        //后屋个人信息数据
        String name = HttpServletRequestUtil.getString(request, "name");
        String sex = HttpServletRequestUtil.getString(request, "sex");

        //判断是否为空
        if (name != null && sex != null){
            //修改数据
            Personal personal = new Personal();
                personal.setUid(uid);
                personal.setName(name);
                personal.setSex(sex);
                //执行sql
                boolean bypersonal = personalService.findBypersonal(personal);
                map.put("success", bypersonal);
            }
        return map;
    }

    /**
     * 后端 个人信息回显
     */
    @GetMapping("/findone")
    @ResponseBody
    public Map<String,Object> personal(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        //获取id
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        Personal id = personalService.findById(uid);
        map.put("ons", id);
        return map;
    }
    

    

    /**
     *  后端 修改个人头像
     */
    @PostMapping("/portraits")
    public Resp<String> findByupdate(MultipartFile file, HttpServletRequest request)throws IOException {
        return personalService.updateImg(file,request);
    }

}

CommodityController

package com.example.jd.Controller;

import com.example.jd.Entity.Commodity;
import com.example.jd.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
//@RequestMapping("/rid")
public class CommodityController {

    @Autowired//实体化
    private CommodityService commodityService;

    /**
     * 商品详情
     * @return
     */
    @GetMapping("/search1")
    public  String search(){
        return "/search";
    }


    /**
     * 前端展示数据库数据
     * @param request
     * @return
     */
    @GetMapping("/findAlls")
    @ResponseBody
    public Map<String, Object> findAll(HttpServletRequest request) {
        //查询全部数据
        List<Commodity> all = commodityService.findAll();
        HashMap<String, Object> map = new HashMap<>();
        map.put("all", all);
        map.put("success", true);
        return map;
    }

    /**
     *  商品详情展示(指定id)

     * @return
     */
    @GetMapping("/searchs")
    @ResponseBody
    public Map<String, Object> search(Integer rid) {
        HashMap<String, Object> map = new HashMap<>();
        Commodity id = commodityService.findById(rid);
        map.put("rid", id);
        return map;
    }

}

CartController

package com.example.jd.Controller;


import com.example.jd.Entity.Cart;
import com.example.jd.Entity.Commodity;
import com.example.jd.Entity.User;
import com.example.jd.service.CommodityService;
import com.example.jd.service.impl.CartServiceImpl;
import com.example.jd.service.impl.CommodityServiceImpl;
import com.example.jd.utils.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
//@RequestMapping("/cid")
public class CartController {

    /**
     * 购物车
     */
    @Autowired
    private CartServiceImpl cartService;

    /**
     * 商品
     */
    @Autowired
    private CommodityService commodityService;


    @GetMapping("/shopping1")
    public String Cart1(){
        return "/shopping";
    }


    /**
     * 根据用户id查询用户购物车
     */
    @GetMapping("/findAllcarts")
    @ResponseBody
    public Map<String,Object> findAllcart(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        //获取id
        Integer uid = (Integer)  request.getSession().getAttribute("uid");
        //查询id
        List<Cart> allcart = cartService.findAllcart(uid);
//        System.out.println(allcart);
        map.put("allcart", allcart);
        return map;
    }


    /**
     * 添加购物车
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/shoppings")
    @ResponseBody
    public Map<String,Object> shoppinga(Integer id ,HttpServletRequest request){
        //创建集合
        HashMap<String, Object> map = new HashMap<>();

        //获取商品id
        Commodity sid = commodityService.findById(id);
        String color = HttpServletRequestUtil.getString(request, "color");
        String version = HttpServletRequestUtil.getString(request, "version");
        String method = HttpServletRequestUtil.getString(request, "method");

        //获取前端传递id
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        //判断是否为空
        if (sid != null && uid !=null){
            //前端传入的数据添加到数据库中
            Cart cart = new Cart();
            cart.setUid(uid);
            cart.setSid(sid.getRid());
            cart.setCname(sid.getRname());
            cart.setPrice(sid.getPrice());

            cart.setNum(1);
            cart.setImg(sid.getImg());

            cart.setColor(color);
            cart.setVersion(version);
            cart.setMethod(method);
            //添加
            boolean increasedp = cartService.increasedp(cart);
            if (increasedp){
                map.put("success", true);
            }
        }else {
            map.put("success", false);
            map.put("Msg", "用户需重新登录");
        }
        return map;
    }


    /**
     * 模糊查询
     * @param request
     * @return
     */
    @GetMapping("/findAllfuzzys")
    @ResponseBody
    public Map<String,Object> findAllfuzzy(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        String user = HttpServletRequestUtil.getString(request, "cname");
        if (user != null){
            List<Cart> allfuzzy = cartService.findAllfuzzy(user);
            map.put("allfuzzy",allfuzzy);
        }else {
            map.put("Msg", "没有此数据");
        }
        return map;
    }

}

写入工具类实现HttpServletRequestUtil接收前端页面数据实现后端操作

HttpServletRequestUtil

package com.example.jd.utils;

import javax.servlet.http.HttpServletRequest;

public class HttpServletRequestUtil {
    public static int getInt(HttpServletRequest request, String key){
        try{
            return Integer.decode(request.getParameter(key));
        }catch (Exception e){
            return -1;
        }
    }

    public static long getLong(HttpServletRequest request, String name) {
        try {
            return Long.valueOf(request.getParameter(name));
        } catch (Exception e) {
            return -1;
        }
    }

    public Double getDouble(HttpServletRequest request,String key){
        try{
            return Double.valueOf(request.getParameter(key));
        }catch (Exception e){
            return -1d;
        }
    }

    public static boolean getBoolean(HttpServletRequest request,String key){
        try {
            return Boolean.valueOf(request.getParameter(key));
        }catch (Exception e){
            return false;
        }
    }

    public static String getString(HttpServletRequest request,String key){
        try {
            String result = request.getParameter(key);
            if (result!=null){
                result=result.trim();
            }
            if ("".equals(result)) {
                result=null;
            }
            return result;
        }catch (Exception e){
            return null;
        }
    }
}

 

配置js拼接数据变为动态

 

posted @ 2023-03-11 14:01  monkey大佬  阅读(409)  评论(0)    收藏  举报