购物车实现1--day16

1.用户退出操作

1.1前置条件
  • 业务说明:
    当用户单击退出按钮之后, 页面应该重定向到系统首页,同时删除cookie和redis的登录信息.

  • 页面分析
    当用户点击退出操作之后,应该利用jt-web服务器中的UserController完成该业务.
    在这里插入图片描述

1.2编辑jt-web的UserController
/**
 * 用户退出:
 * url: http://www.jt.com/user/logout.html
 * 没有传递参数
 * 返回值:String		重定向返回系统首页 
 * 业务实现思路:
 * 		先获取cookie中的数据 NAME=JT_TICKET
 * 		1.删除redis中数据     key-value		key=cookie中的value
 * 		2.删除Cookie记录 	根据cookie名称	设置存活时间即可
 * 
 * 注意事项:request对象中只能传递cookie的那么和value.不能传递其他数据参数
 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request,HttpServletResponse response) {

		Cookie[] cookies = request.getCookies();//获取所有的cookie
		if(cookies !=null || cookies.length>0) {//如果cookie为0或长度不大于0则直接返回重定向到首页
			for (Cookie cookie : cookies) {//遍历cookie
				if("JT_TICKET".equalsIgnoreCase(cookie.getName())) {//找到key为JT_TICKET的cookie
					String ticket =cookie.getValue();
					//删除redis
					jedisCluster.del(ticket);
					//删除cookie
					cookie.setDomain("jt.com");   //jt.com结尾的可以域名,实现Cookie数据的共享
					cookie.setPath("/");
					cookie.setMaxAge(0);//立即删除:0/暂时不删,关闭浏览器删除:-0;
					//将Cookie保存到客户端
					response.addCookie(cookie);
					break;
				}
			}
		}
		//转发forward:/
		return "redirect:/";//重定向到系统首页
	}
1.3提取
package com.jt.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    /**
     * 该工具API主要的任务
     *      1.根据cookie的名称 返回cookie对象
     *      2.根据cookie的名称 返回valve的值
     *      3.新增cookie方法
     *      4.删除cookie方法
     */
    public static Cookie getCookie(String cookieName, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies !=null && cookies.length >0) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null ;
    }

    public static String getCookieValue(String cookieName,HttpServletRequest request){
        Cookie cookie = getCookie(cookieName, request);
        return cookie ==null?null:cookie.getValue();
    }

    public static void addCookie(String cookieName, String cookieValue, String path,
                                 String domain, int maxAge, HttpServletResponse response){
        Cookie cookie = new Cookie(cookieName,cookieValue);
        cookie.setPath(path);
        cookie.setDomain(domain);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static void deleteCookie(String cookieName,String path,
                                    String domain,HttpServletResponse response){

        addCookie(cookieName,"",path, domain, 0, response);
    }

}


    @RequestMapping("/logout")
    private String logout(HttpServletRequest request, HttpServletResponse response{
        String ticket = CookieUtil.getCookieValue("JT_TICKET", request);
        if(!StringUtils.isEmpty(ticket)){
            //1.删除redis
            jedisCluster.del(ticket);
            //2.删除cookie
            CookieUtil.deleteCookie("JT_TICKET", "/", "jt.com", response);
        }
        //重定向到系统首页
        return "redirect:/";
   }

2 商品数据展现

2.1前置条件
  • 业务描述
    当用户看中某一个商品时,点击该商品,应该展现的是商品的详情信息.
    在这里插入图片描述
  • 将JT-MANAGE项目改造为Dubbo项目
package com.jt.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.jt.service.DubboItemService;

@Service
public class DubboItemServiceImpl implements DubboItemService {

@Autowired
private ItemMapper itemMapper;
@Autowired
private ItemDescMapper itemDescMapper;

}
  • 编辑manage.jt.com的yml配置文件, 注意duubo端口号及dubbo服务名称
server:
  port: 8091
  servlet:
    context-path: /
spring:
  datasource:
    #引入druid数据源
    #type: com.alibaba.druid.pool.DruidDataSource
    #driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: 密码

  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
#mybatis-plush配置
mybatis-plus:
  type-aliases-package: com.jt.pojo
  mapper-locations: classpath:/mybatis/mappers/*.xml
  configuration:
    map-underscore-to-camel-case: true

logging:
  level: 
    com.jt.mapper: debug

#关于Dubbo配置   
dubbo:
  scan:
    basePackages: com.jt    #指定dubbo的包路径
  application:              #应用名称
    name: provider-manage    #一个接口对应一个服务名称
  registry:
    address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183,192.168.126.129:2184,192.168.126.129:2185
  protocol:  #指定协议
    name: dubbo  #使用dubbo协议(tcp-ip)  web-controller直接调用sso-Service
    port: 20881  #每一个服务都有自己特定的端口 不能重复.  
    
2.2编辑JT-WEB ItemController
package com.jt.controllor;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.DubboItemService;

@Controller
@RequestMapping("/items")
public class ItemController {
	
	@Reference(check = false) //启动时暂时不校验提供者
	private DubboItemService itemService;
	
	/**
	 * http://www.jt.com/items/562379.html  跳转到商品页面
	 * ${item.title }  商品信息
	 * ${itemDesc.itemDesc } 商品详情信息
	 * 
	 * 业务说明: 根据商品id查询执行的商品/商品详情信息,之后在页面中展现.
	 * @param itemId
	 * @return
	 */
	@RequestMapping("/{itemId}")
	public String findItemById(@PathVariable Long itemId,Model model) {
		
		Item item = itemService.findItemById(itemId);
		ItemDesc itemDesc = itemService.findItemDescById(itemId);
		model.addAttribute("item", item);
		model.addAttribute("itemDesc", itemDesc);
		return "item";  //item.jsp
	}
}
2.3编辑JT-MANAGE ItemService
package com.jt.web.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.DubboItemService;

@Service
public class DubboItemServiceImpl implements DubboItemService {

@Autowired
private ItemMapper itemMapper;
@Autowired
private ItemDescMapper itemDescMapper;
@Override
public Item findItemById(Long itemId) {
	return itemMapper.selectById(itemId);
}
@Override
public ItemDesc findItemDescById(Long itemId) {
	return itemDescMapper.selectById(itemId);
}	
}
2.4效果

在这里插入图片描述

3 定义购物车模块

3.1根据表设计pojo

package com.jt.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import lombok.Data;
import lombok.experimental.Accessors;
@Accessors(chain = true)
@Data
@TableName("tb_cart")
public class Cart extends BasePojo{

	@TableId(type = IdType.AUTO)
	private Long id;			//id
	private Long userId;		//用户
	private Long itemId;		//商品
	private String itemTitle;	//标题
	private String itemImage;	//主图
	private Long itemPrice;		//价格
	private Integer num;		//购买数量

}

3.2添加jt-cart模块

  • 启动类
package com.jt;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.jt.mapper")
public class SpringBootRun {
	
	public static void main(String[] args) {
		
		SpringApplication.run(SpringBootRun.class, args);
	}
}

配置application文件

server:
  port: 8094
  servlet:
    context-path: /
spring:
  datasource:
    #引入druid数据源
    #type: com.alibaba.druid.pool.DruidDataSource
    #driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: 密码

  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
#mybatis-plush配置
mybatis-plus:
  type-aliases-package: com.jt.pojo
  mapper-locations: classpath:/mybatis/mappers/*.xml
  configuration:
    map-underscore-to-camel-case: true

logging:
  level: 
    com.jt.mapper: debug

#关于Dubbo配置   
dubbo:
  scan:
    basePackages: com.jt    #指定dubbo的包路径
  application:              #应用名称
    name: provider-cart    #一个接口对应一个服务名称
  registry:
    address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183,192.168.126.129:2184,192.168.126.129:2185
  protocol:  #指定协议
    name: dubbo  #使用dubbo协议(tcp-ip)  web-controller直接调用sso-Service
    port: 20882  #每一个服务都有自己特定的端口 不能重复.  
    
    
    
    
  • 添加CartMapper
package com.jt.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jt.pojo.Cart;

public interface CartMapper extends BaseMapper<Cart>{

}

  • 添加DubboCartServiceImpl
package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;

@Service //(timeout = 10000)	//dubbo service注解	10秒超时 内部实现rpc
public class DubboCartServiceImpl implements DubboCartService {

}

3.2 在jt-web添加CartController

package com.jt.controllor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.service.DubboCartService;

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

	@Reference(check = false)
	private DubboCartService cartService;
	
	@RequestMapping("show")
	public String show() {
		return "cart";
	}
	
}

4 购物车打开

4.1修改CartController

package com.jt.controllor;

import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;

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

	@Reference(check = false)
	private DubboCartService cartService;
	
	@RequestMapping("show")
	public String show(Model model) {
		//1.获取userId	利用单点登入的方式获取userId   暂时写死
		Long userId =7L;
		//2.根据userId查询公务车数据
		List<Cart> cartList =cartService.findCartListByUserId(userId);
		
		model.addAttribute("cartList",cartList);
		return "cart";
	}
}

4.2修改DubboCartServiceImpl

package com.jt.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;

@Service //(timeout = 10000)	//dubbo service注解	10秒超时 内部实现rpc
public class DubboCartServiceImpl implements DubboCartService {

	@Autowired
	private CartMapper cartMapper;
	
	@Override
	public List<Cart> findCartListByUserId(Long userId) {
		QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
		queryWrapper.eq("user_id", userId);
	
		return cartMapper.selectList(queryWrapper);
	}
}

5 购物车加/减商品数量 分析

在这里插入图片描述

在这里插入图片描述
http://www.jt.com/cart/update/num/{itemId}/{num}

5.1编辑CartController

	/**
	 * 业务需求: 完成购物车商品跟新操作
	 * 1.url:http://www.jt.com/cart/update/num/562379/9
	 * 2.请求参数:562379-itemId		9-num
	 * 3.返回值结果:void
	 */
	@RequestMapping("/update/num/{itemId}/{num}")
	@ResponseBody
	public void updateCart(Cart cart) {	//参数如果和属性名称一致则可以直接赋值.
		Long userId =7L;
		cart.setUserId(userId);
		cartService.updateCartNum(cart);
	}

5.2编辑DubboCartServiceImpl

	@Override
	public void updateCartNum(Cart cart) {
		Cart cart1=new Cart();
		cart1.setNum(cart.getNum());
		
		
		UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<Cart>();
		
		updateWrapper.eq("item_id", cart.getItemId())
					 .eq("user_id", cart.getUserId());
		cartMapper.update(cart1, updateWrapper);
	}

6 购物车新增

  • 业务分析
    当查询商品之后,点击新增购物车时.应该跳转到购物车展现页面. 之后完成购物车新增操作.
    强调:
    1.当用户第一次新增购物车时,应该入库保存
    2.当用户重复添加时,应该只更新商品的数量.

6.1编辑jt-web CartController

	/**
	 * url:http://www.jt.com/cart/add/562379.html
	 * 参数:Cart
	 * 返回值:重定向到购物车页面
	 */
	@RequestMapping("add/{itemId}")
	public String saveCart(Cart cart) {
		Long userId =7L;
		cart.setUserId(userId);
		cartService.saveCart(cart);
		return "redirect:/cart/show.html";
	}

6.2编辑DubboCartServiceImpl

	@Override
	public void saveCart(Cart cart) {
		//1.查询数据库中是否有该记录 itemId和userId
		QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
		queryWrapper.eq("item_id", cart.getItemId())
					.eq("user_id", cart.getUserId());
		Cart cartDB =cartMapper.selectOne(queryWrapper);
		
		if(cartDB==null) {//说明是第一次
			cart.setCreated(new Date())
				.setUpdated(cart.getCreated());
			cartMapper.insert(cart);
		}else {//只跟新商品数量
			int num =cart.getNum()+cartDB.getNum();

			//生成代码
//			Cart cart1 =new Cart();
//			cart1.setNum(cart.getNum())
//				.setId(cartDB.getId())
//				.setUpdated(new Date());
//			cartMapper.updateById(cart1);
			//手写sql代码
			cartMapper.updateCartNum(cartDB.getId(),num,new Date());
		}
	
	}

ps:手写在mapper里面写

@Update("update tb_cart set num=#{num},updated=#{date} where id=#{id}")
	void updateCartNum(Long id, int num, Date date);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值