1. User module implementation
1.1 User information echo
1.1.1 page URL analysis
1.1.2 Check the page JS
1.1.3 edit JT-SSO Of Controller
`/**
* Business implementation :
* 1. User pass cookie Information query user data . adopt ticket obtain redis Business data in .
* 2.url request : http://sso.jt.com/user/query/+ _ticket
* 3. Parameters : Parameter in url in . utilize restFul obtain
* 4. The return value requires : SysResult object (userJSON)
*/
@RequestMapping("/query/{ticket}")
public JSONPObject findUserByTicket(@PathVariable String ticket,
HttpServletResponse response,
String callback){
String userJSON = jedisCluster.get(ticket);
//1.lru The algorithm clears the data 2. There may be cookie The information is wrong
if(StringUtils.isEmpty(userJSON)){
//2. Should delete cookie Information .
Cookie cookie = new Cookie("JT_TICKET", "");
cookie.setMaxAge(0);
cookie.setDomain("jt.com");
cookie.setPath("/");
response.addCookie(cookie);
return new JSONPObject(callback,SysResult.fail());
}
return new JSONPObject(callback,SysResult.success(userJSON));
}`
1.2 edit Cookie Tools API
`package com.jt.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieUtil {
//1. newly added cookie
public static void addCookie(HttpServletResponse response,String cookieName, String cookieValue, int seconds, String domain){
Cookie cookie = new Cookie(cookieName,cookieValue);
cookie.setMaxAge(seconds);
cookie.setDomain(domain);
cookie.setPath("/");
response.addCookie(cookie);
}
//2. according to name Inquire about value Value
public static String getCookieValue(HttpServletRequest request,String cookieName){
Cookie[] cookies = request.getCookies();
if(cookies !=null && cookies.length >0){
for (Cookie cookie : cookies){
if(cookieName.equals(cookie.getName())){
return cookie.getValue();
}
}
}
return null;
}
//3. Delete cookie
public static void deleteCookie(HttpServletResponse response,String cookieName,String domain){
addCookie(response,cookieName,"",0, domain);
}
}`
1.3 User exit operation
1.3.1 Business description
If the user clicks exit operation , First of all, we should delete Redis Data in Next delete Cookie Data in Then redirect to the system home page .
1.3.2 URL analysis
1.3.3 edit UserController
`/**
* User exit operation . Redirect to system home page
* url: http://www.jt.com/user/logout.html
* Business :
* 1. Delete Redis Data in key
* 2. Delete Cookie Record
*/
@RequestMapping("logout")
public String logout(HttpServletRequest request,HttpServletResponse response){
//1. according to JT_TICKET Get the specified ticket
String ticket = CookieUtil.getCookieValue(request,"JT_TICKET");
//2. Judge ticket Is it null
if(!StringUtils.isEmpty(ticket)){
jedisCluster.del(ticket);
CookieUtil.deleteCookie(response,"JT_TICKET","jt.com");
}
return "redirect:/";
}`
2 Realize the display of product details
2.1 Business description
explain : When a user clicks on a product , Need to jump to the product display page Page name item.jsp
2.2 restructure JT-MANAGE
2.2.1 Create an interface
explain : stay jt-common Create interface in
2.2.2 edit Dubbo Implementation class
`package com.jt.service;
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 org.springframework.beans.factory.annotation.Autowired;
@Service(timeout = 3000)
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.2.3 edit YML The configuration file
`server:
port: 8091
servlet:
context-path: /
spring:
datasource:
# introduce druid data source
#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: root
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
#mybatis-plush To configure
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
# About Dubbo To configure
dubbo:
scan:
basePackages: com.jt # Appoint dubbo The package path of scanning dubbo annotation
application: # apply name
name: provider-manage # An interface corresponds to a service name An interface can have multiple implementations
registry: # Registry Center The user gets the data from the machine The host is only responsible for monitoring the entire cluster Data synchronization
address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183
protocol: # Designated agreement
name: dubbo # Use dubbo agreement (tcp-ip) web-controller Call directly sso-Service
port: 20881 # Each service has its own specific port Can't repeat .`
2.2.4 edit ItemController
`package com.jt.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.DubboItemService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/items")
public class ItemController {
@Reference(timeout = 3000)
private DubboItemService itemService;
/**
* Realize product details page Jump
* url: http://www.jt.com/items/562379.html
* Parameters : 562379 itemId
* Return value : item.jsp page
* Page value description :
* ${item.title } item object
* ${itemDesc.itemDesc } itemDesc object
*
* Ideas :
* 1. restructure jt-manage project
* 2. Create a neutral interface DubboItemService
* 3. Achieve business call acquisition item/itemDesc object
*/
@RequestMapping("/{itemId}")
public String findItemById(@PathVariable Long itemId, Model model){
Item item = itemService.findItemById(itemId);
ItemDesc itemDesc = itemService.findItemDescById(itemId);
// Save data to request domain
model.addAttribute("item",item);
model.addAttribute("itemDesc",itemDesc);
return "item";
}
}`
2.2.5 Page effect display
3 Shopping Cart module implementation
3.1 Create service provider
3.1.1 Create project JT-CART
3.1.2 Add inheritance / rely on / plug-in unit
`<!--2. Add dependency information -->
<dependencies>
<!-- What depends essentially on is jar Package file -->
<dependency>
<groupId>com.jt</groupId>
<artifactId>jt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!--3. Add the plug-in -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>`
3.1.3 edit POJO object
`@TableName("tb_cart")
@Data
@Accessors(chain = true)
public class Cart extends BasePojo{ // Use packaging type
@TableId(type = IdType.AUTO)
private Long id;
private Long uesrId; // user ID Number
private Long itemId; // goods ID Number
private String itemTitle; // Commodity title
private String itemImage; // picture
private Long itemPrice; // commodity price
private Integer num; // The number
}`
3.1.4 edit CartService Interface
3.1.5 jt-cart The code structure
3.2 Shopping cart list page shows
3.2.1 page url analysis
explain : When the user clicks on the shopping cart button , Need to jump to the cart display page . cart.jsp
Page value : ${cartList}
requirement : Query only userId=7 Shopping cart list information for . After that, the page will be displayed
3.2.2 edit CartController
`package com.jt.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/cart")
public class CartController {
@Reference(timeout = 3000,check = false)
private DubboCartService cartService;
/**
* Business needs : according to userId Query shopping cart data
* url Address : http://www.jt.com/cart/show.html
* Request parameters : Get dynamic userId
* Return value result : cart.jsp page
* Page value method : ${cartList}
*/
@RequestMapping("/show")
public String findCartListByUserId(Model model){
Long userId = 7L;
List<Cart> cartList = cartService.findCartListByUserId(userId);
model.addAttribute("cartList",cartList);
return "cart";
}
}`
3.2.3 edit CartService
`package com.jt.service;
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;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Service
public class DubboCartServiceImpl implements DubboCartService{
@Autowired
private CartMapper cartMapper;
@Override
public List<Cart> findCartListByUserId(Long userId) {
QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", userId);
return cartMapper.selectList(queryWrapper);
}
}`
3.2.4 Page effect display
3.3 Modification of the number of shopping carts
3.3.1 Business description
3.3.2 page JS analysis
3.3.3 edit CartController
`/**
* Business : Update the number of shopping carts
* url: http://www.jt.com/cart/update/num/562379/12
* Parameters : itemId/num
* Return value : void
*/
@RequestMapping("/update/num/{itemId}/{num}")
@ResponseBody //1. The return value is converted to json 2.ajax End identification
public void updateCartNum(Cart cart){ //key The name must match the name of the property .
Long userId = 7L;
cart.setUserId(userId);
cartService.updateCartNum(cart);
}`
3.3.4 edit CartService
`@Override
public void updateCartNum(Cart cart) {
//cartMapper.updateCartNum(cart);
//1. Ready to modify the data According to the object is not null The elements of as set Conditions
Cart cartTemp = new Cart();
cartTemp.setNum(cart.getNum());
//2. According to the object is not null The elements of as where Conditions
UpdateWrapper<Cart> updateWrapper =
new UpdateWrapper<>(cart.setNum(null));
/*updateWrapper.eq("user_id", cart.getUserId())
.eq("item_id", cart.getItemId());*/
cartMapper.update(cartTemp,updateWrapper);
}`
3.3.5 edit CartMapper
`public interface CartMapper extends BaseMapper<Cart> {
@Update("update tb_cart set num = #{num},updated=now() where user_id=#{userId} and item_id=#{itemId}")
void updateCartNum(Cart cart);
}`
* 1
* 2
* 3
* 4
3.4 Shopping cart added
3.4.1 Shopping cart new business
When the user clicks the shopping cart button, the shopping cart is put into storage . If the user makes repeated purchases, the number of items in the shopping cart should be modified .
After the success of the purchase , Should be redirected to the shopping cart list page .
3.4.2 Page analysis
3.4.3 Page form submission
`<form id="cartForm" method="post">
<input class="text" id="buy-num" name="num" value="1" onkeyup="setAmount.modify('#buy-num');"/>
<input type="hidden" class="text" name="itemTitle" value="${item.title }"/>
<input type="hidden" class="text" name="itemImage" value="${item.images[0]}"/>
<input type="hidden" class="text" name="itemPrice" value="${item.price}"/>
</form>`
3.4.4 page JS analysis
`<a class="btn-append " id="InitCartUrl" onclick="addCart();" clstag="shangpin|keycount|product|initcarturl"> Add to cart <b></b></a>
// utilize post Pass value
function addCart(){
var url = "http://www.jt.com/cart/add/${item.id}.html";
document.forms[0].action = url; //js Set submit link
document.forms[0].submit(); //js Form submission
}`
3.4.5 edit CartController
`/**
* Complete shopping cart addition
* url: http://www.jt.com/cart/add/562379.html
* Parameters : form Form submission Object reception
* Return value : Redirect to cart list page
*/
@RequestMapping("/add/{itemId}")
public String saveCart(Cart cart){
Long userId = 7L;
cart.setUserId(userId);
cartService.saveCart(cart);
return "redirect:/cart/show.html";
}`
3.4.6 edit CartService
`/**
* If repeat purchase, update quantity
* 1. Query whether the data has been changed user_id/item_id
*/
@Override
public void saveCart(Cart cart) {
QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", cart.getUserId())
.eq("item_id", cart.getItemId());
Cart cartDB = cartMapper.selectOne(queryWrapper);
if(cartDB == null){
// The first time the user bought
cartMapper.insert(cart);
}else {
// The user needs to modify the quantity
int num = cart.getNum() + cartDB.getNum();
cart.setNum(num);
cartMapper.updateCartNum(cart);
}
}`
3.4.6 Page effects