Day09:SpringCloud购物车Demo

本文详细介绍了SpringCloud购物车Demo的实现,包括Provider、Consumer的构建以及Zuul的配置。讲解了jsp与thymeleaf的区别,指出thymeleaf作为主流模板引擎的原因。在Provider部分,涉及了POJO、Mapper、Service和Controller的创建。Consumer部分介绍了Feign接口的使用和操作。最后,对Zuul的配置进行了调整,包括fallback和yaml的修改。
摘要由CSDN通过智能技术生成

PO,PersistenceObject,持久化对象,针对数据库
VO,ViewObject,视图对象,针对页面jsp,pdf,excel,模板对象freemarker,thymeleaf3.0
BO,BusinessObject业务对象,复杂业务
POJO,简单java对象。

jsp和thymeleaf区别?

Thymeleaf成为主流方式?
1、jsp浏览器是否直接解析,在没有servlet容器情况下。
2、jsp通过el+jstl标签解析,学习成本高,c:forEach
3、thymeleaf空冲了页面的标准的html标签,html标签可以直接被浏览器解析,浏览器非常弱 ,它允许代码中有错误。对错误忽略跳过。
4、模板通过特殊的一些标志,数据<table c:foreach>,脱离servlet容器
5、Main函数驱动类,脱离servlet容器,增加thymeleaf包依赖,解析html之前,依赖包会配置数据,然后翻译页面增强属性,替换成数据。

准备工作:
1、SQLyog
2、jt-db
在这里插入图片描述
3、拷贝Eureka和Zuul【Zuul在最后会修改application-name】

====================================

一、Provider

新建jt-cart-provider
1、pom

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
		<relativePath />
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring-cloud.version>Dalston.SR1</spring-cloud.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<!-- mybatisplus/mybatis/jdbc/druid -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- mybatisplus与springboot整合 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatisplus-spring-boot-starter</artifactId>
			<version>1.0.5</version>
		</dependency>
		<!-- MP 核心库 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus</artifactId>
			<version>2.1.8</version>
		</dependency>
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- alibaba的druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.0</version>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

2、SysResult【返回工具类】

 // 响应业务状态
    /*
     * 200	成功
     * 201	错误
     * 400	参数错误
     */
    private Integer status;// 响应消息
    private String msg;// 响应中的数据
    private Object data;

3、POJO
①BasePojo

	private Date created;
	private Date updated;
	public Date getCreated() {
		return created;
	}
	public void setCreated(Date created) {
		this.created = created;
	}
	public Date getUpdated() {
		return updated;
	}
	public void setUpdated(Date updated) {
		this.updated = updated;
	}

②POJO

@TableName("tb_cart")//对应的表
public class Cart extends BasePojo {

	
	@TableId(type=IdType.AUTO)
	private Long id;
	
	private Long userId;
	private Long itemId;
	private String itemTitle;
	private String itemImage;
	private Long item_price;
	private Integer num;

4、Mapper

public interface CartMapper extends BaseMapper<Cart>{
}

5、Service

//	按id查询购物车【我的购物车】
	public List<Cart> query(Long userId);
	
//	删除http://cart.jt.com/cart/delete/{userId}/{itemId}【删除购物车中商品】
	public void delete(Long userId,Long itemId);
	
//	新增商品【加入购物车】http://cart.jt.com/cart/save
//	userId 用户ID、itemId 商品ID、itemTitle 商品标题、itemImage 商品主图、itemPrice 商品价格、num 商品数量
	public SysResult save(Cart cart);
	
	//更新商品数量 - + ,页面的值直接替换数据库的值 /cart/update/num/{userId}/{itemId}/{num}
	public void updateNum(Cart cart);
@Service
public class CartServiceImpl implements CartService{

	@Autowired
	private CartMapper cartMapper;

//	按id查看
	public List<Cart> query(Long userId) {
		// TODO Auto-generated method stub
		
		EntityWrapper<Cart> wrapper = new EntityWrapper<Cart>();
		wrapper.where("user_id={0}", userId);
		return cartMapper.selectList(wrapper);
	}
	
//  删除 	http://cart.jt.com/cart/delete/{userId}/{itemId}
	public void delete(Long userId, Long itemId) {
		EntityWrapper<Cart> wrapper = new EntityWrapper<Cart>();
		wrapper.where("user_Id={0}", userId);
		wrapper.and("item_id", itemId);//and连接后续条件
		cartMapper.delete(wrapper);
		
	}

//	加入购物车 http://cart.jt.com/cart/save    200成功,201失败,202已经存在,400参数不合法
	public SysResult save(@RequestBody Cart cart) {
//		1、判断此商品是否存在
		Cart param = new Cart();
		param.setUserId(cart.getUserId());//将当前输入的cart获取到的UserId赋值给param对象
		param.setItemId(cart.getItemId());//将当前输入的cart获取到的ItemId赋值给param对象
//		如果param的现有内容被select查到了【非null】==》说明重复。
//		如果没被查到==》null--》新增
//		所以假设param的内容是已有内容,就为oldCart
		Cart oldCart = cartMapper.selectOne(param);//pojo,属性怎么出现在where条件中的,属性是否为null,为null不出现,不为null出现
//		2、如果不存在,新建操作
		if(oldCart==null) {
			cart.setCreated(cart.getCreated());
			cart.setUpdated(cart.getUpdated());
			cartMapper.insert(cart);
			return SysResult.ok();
		}else {//3、如果存在,那么这个对象是旧的Cart,修改旧的信息,数量=【旧的数量+新的数量】
			oldCart.setNum(oldCart.getNum()+cart.getNum());
			cartMapper.updateById(oldCart);
			return SysResult.build(202, "该商品已经存在购物车中!");
		}
	}

	
	//更新商品数量 - + ,页面的值直接替换数据库的值 /cart/update/num/{userId}/{itemId}/{num}
	public void updateNum(Cart cart) {
		EntityWrapper<Cart> wrapper = new EntityWrapper<Cart>();
		wrapper.where("user_id={0}", cart.getUserId());
		wrapper.and("item_id={0}",cart.getItemId());
		cart.setUpdated(new Date());
		cartMapper.update(cart, wrapper);
	}
	
}

6、Controller

@RestController
public class CartController {

	@Autowired
	private CartService cartService;
	
//	id查询结果         http://cart.jt.com/cart/query/7
//  status: 200  //200 成功,201 没有查到
	@RequestMapping("/cart/query/{userId}")
	public SysResult query(@PathVariable("userId") Long userId) {
		try {
			List<Cart> cartList =cartService.query(userId);
			return SysResult.ok(cartList);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return SysResult.build(201, "查询商品失败");
		}
//		参数如何传递  [将service调用方法query根据userId查找出来的结果,存储到Cart类型的List中]
//		如何返回SYSResult[如果查询成功了 返回ok和cartList的内容,查询失败 返回201.通过try-catch]
	}
	
//	删除 http://cart.jt.com/cart/delete/{userId}/{itemId}
	@RequestMapping("/cart/delete/{userId}/{itemId}")
	public SysResult delete(
			@PathVariable("userId") Long userId,
			@PathVariable("itemId") Long itemId) {
		try {
			cartService.delete(userId, itemId);
			return SysResult.ok();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return SysResult.build(201, "删除商品失败");
		}
	}
	
	
//	加入购物车            http://cart.jt.com/cart/save
	@RequestMapping("/cart/save") //以post请求来访问 需要工具类HttpClient
	public SysResult save(@RequestBody Cart cart) {
		return cartService.save(cart);
	}
	
//更新商品数量 - + ,页面的值直接替换数据库的值 /cart/update/num/{userId}/{itemId}/{num}
	@RequestMapping("/cart/updateNum") 
	public SysResult updateNum(@RequestBody Cart cart) {
		
		try {
			cartService.updateNum(cart);
			return SysResult.ok();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return SysResult.build(201, "更新商品数量失败");
		}
		
	}
}

7、启动类【一定要是@SpringBootApplication】

@SpringBootApplication
@EnableEurekaClient
@MapperScan("com.zz.mappers")
public class RunApplicationProvider {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		SpringApplication.run(RunApplicationProvider.class, args);
	}

}

8、调试工具

package com.zz.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Test;

public class HttpClientPost {
	@Test
	public void form() throws Exception {
		String url = "http://localhost:7900/cart/save";
		Map<String, String> paraMap = new HashMap<String,String>();
		
		paraMap.put("userId", "7");
		paraMap.put("itemId", "20");
		paraMap.put("itemTitle", "title");
		paraMap.put("itemImage", "image");
		paraMap.put("itemPrice", "17");
		paraMap.put("num", "2");
		
		String result = httpPostWithForm(url,paraMap);
		System.out.println(result);
	}

	public static String httpPostWithForm(String url, Map<String, String> paraMap) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient client = HttpClients.createDefault();
		String respContent = null;

		//遍历参数map,设置表单参数
		List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
		for (Map.Entry<String, String> entry : paraMap.entrySet()) {
			pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));

		HttpResponse resp = client.execute(httpPost);
		if (resp.getStatusLine().getStatusCode() == 200) {
			HttpEntity he = resp.getEntity();
			respContent = EntityUtils.toString(he, "UTF-8");
		}
		return respContent;
	}

	@Test
	public void json() throws Exception {
		String url = "http://localhost:7900/cart/updateNum";
		String result = httpPostWithJSON(url);
		System.out.println(result);
	}

	public static String httpPostWithJSON(String url) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient client = HttpClients.createDefault();
		String respContent = null;

		// json方式
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("userId", "7");
		jsonParam.put("itemId", "20");
//		jsonParam.put("itemTitle", "title");
//		jsonParam.put("itemImage", "image");
//		jsonParam.put("itemPrice", "120");
		jsonParam.put("num", "33");

		StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);

		HttpResponse resp = client.execute(httpPost);
		if (resp.getStatusLine().getStatusCode() == 200) {
			HttpEntity he = resp.getEntity();
			respContent = EntityUtils.toString(he, "UTF-8");
		}
		return respContent;
	}

}

结果:

按id查询
在这里插入图片描述
删除某用户的某商品
在这里插入图片描述
加入购物车
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
更新商品数量
在这里插入图片描述
在这里插入图片描述

二、Consumer

1、pom文件

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
		<relativePath />
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring-cloud.version>Dalston.SR1</spring-cloud.version>
	</properties>
	<dependencies>
	
	<!-- 配置Eureka注册中心 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		
		<!-- hystrix熔断器 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
		
		<!-- Feign进行RESTFul封装 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		<!-- web级应用 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

2、准备Feign接口(拷贝Provider的Controller方法)

//Feign客户端路径 指向Provider的Application-name
@FeignClient("jt-cart-provider")
public interface CartFeign {

	@RequestMapping("/cart/query/{userId}")
	public SysResult query(@PathVariable("userId") Long userId);

	// 删除 http://cart.jt.com/cart/delete/{userId}/{itemId}
	@RequestMapping("/cart/delete/{userId}/{itemId}")
	public SysResult delete(
			@PathVariable("userId") Long userId,
			@PathVariable("itemId") Long itemId);

	// 加入购物车 http://cart.jt.com/cart/save
	@RequestMapping("/cart/save") // 以post请求来访问 需要工具类HttpClient
	public SysResult save(@RequestBody Cart cart);

	// 更新商品数量 - + ,页面的值直接替换数据库的值 /cart/update/num/{userId}/{itemId}/{num}
	@RequestMapping("/cart/updateNum")
	public SysResult updateNum(@RequestBody Cart cart);
}

3、Controller

@RestController
public class CartController {

	//与Feign建立联系
	@Autowired
	private CartFeign cartFeign;
	
//	id查询结果         http://cart.jt.com/cart/query/7
	@RequestMapping("/cart/query/{userId}")
	public SysResult query(@PathVariable("userId") Long userId) {
		return cartFeign.query(userId);
	}

	// 删除 http://cart.jt.com/cart/delete/{userId}/{itemId}
	@RequestMapping("/cart/delete/{userId}/{itemId}")
	public SysResult delete(
			@PathVariable("userId") Long userId,
			@PathVariable("itemId") Long itemId) {
		return cartFeign.delete(userId, itemId);
	}

	// 加入购物车 http://cart.jt.com/cart/save
	@RequestMapping("/cart/save") // 以post请求来访问 需要工具类HttpClient
	public SysResult save(@RequestBody Cart cart) {
		return cartFeign.save(cart);
	}

	// 更新商品数量 - + ,页面的值直接替换数据库的值 /cart/update/num/{userId}/{itemId}/{num}
	@RequestMapping("/cart/updateNum")
	public SysResult updateNum(@RequestBody Cart cart) {
		return cartFeign.updateNum(cart);
	}
}

4、yaml

server:
  port: 9001

spring:
  application:
    name: jt-cart-consumer

eureka:
  client:
    serviceUrl:
      defaultZone: http://user:password123@localhost:8761/eureka

logging:
  level:
    root: INFO

5、入口类

@SpringCloudApplication
@EnableFeignClients
public class RunApplicationConsumer {
	public static void main(String[] args) {
		SpringApplication.run(RunApplicationConsumer.class, args);
	}
}

在这里插入图片描述
新增:
在这里插入图片描述
修改:
在这里插入图片描述
删除:
在这里插入图片描述

三、配置Zuul

1、fallback修改

在这里插入图片描述

2、yaml修改

zuul:
  ignoredServices: '*'
  routes:
    app-provider-user:            
      path: /jt/**
      serviceId: jt-cart-consumer

在这里插入图片描述
查看:
在这里插入图片描述
加入、修改【到provider的util中测试】

@Test
	public void form() throws Exception {
//		String url = "http://localhost:7900/cart/save";
		String url = "http://localhost:8050/jt/cart/save";
		Map<String, String> paraMap = new HashMap<String,String>();
		
		paraMap.put("userId", "2");
		paraMap.put("itemId", "20");
		paraMap.put("itemTitle", "title");
		paraMap.put("itemImage", "image");
		paraMap.put("itemPrice", "17");
		paraMap.put("num", "2");
		
		String result = httpPostWithForm(url,paraMap);
		System.out.println(result);
	}

	public static String httpPostWithForm(String url, Map<String, String> paraMap) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient client = HttpClients.createDefault();
		String respContent = null;

		//遍历参数map,设置表单参数
		List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
		for (Map.Entry<String, String> entry : paraMap.entrySet()) {
			pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));

		HttpResponse resp = client.execute(httpPost);
		if (resp.getStatusLine().getStatusCode() == 200) {
			HttpEntity he = resp.getEntity();
			respContent = EntityUtils.toString(he, "UTF-8");
		}
		return respContent;
	}

加入购物车:
原无:

在这里插入图片描述
在这里插入图片描述
原有新增:
在这里插入图片描述
在这里插入图片描述
修改数量:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值