当前位置:网站首页>In the third stage, the day20 Shopping Cart module is added, the interceptor is added, the user authority is checked, and the order module is realized

In the third stage, the day20 Shopping Cart module is added, the interceptor is added, the user authority is checked, and the order module is realized

2020-11-09 16:55:00 Half bump

  1. Shopping cart delete operation

===========

1.1 Page analysis

 Insert picture description here

1.2 edit CartController

 `/**
     *  Shopping cart delete operation 
     * url Address : http://www.jt.com/cart/delete/562379.html
     *  Parameters :     obtain itemId
     *  Return value :   Redirect to the presentation page of the shopping cart 
     */
    @RequestMapping("/delete/{itemId}")
    public String deleteCarts(@PathVariable Long itemId){

        Long userId = 7L;
        cartService.deleteCarts(userId,itemId);
        return "redirect:/cart/show.html";
    }` 



1.3 edit CartService

 `@Override
    public void deleteCarts(Long userId, Long itemId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("item_id", itemId);
        cartMapper.delete(queryWrapper);
    }` 

  1. Jingtao permissions to achieve

==========

2.1 Business needs

When a user makes sensitive operations , Users must be required to log in before they can access the back-end server . For example, Jingdong Mall …
Using technology :
1.AOP
2. Interceptor : Block user requests
 Insert picture description here

2.2 Define Jingtao interceptor

2.2.1 SpringMVC Call schematic  Insert picture description here

2.2.2 SpringMVC How interceptors work

 Insert picture description here

2.2.3 Configure interceptors

`@Component  //spring Container management object 
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisCluster jedisCluster;

    //Spring Version update  4  All methods have to be implemented   spring 5  Just override the specified method .

    /**
     *  demand :    Intercept /cart All requests at the beginning are intercepted ., And verify that the user is logged in .....
     *  Interceptor selection : preHandler
     *  How to determine whether a user is logged in :  1. Check cookie Information    2. Check Redis Is there a record in .
     *          true :  The request should be released 
     *          false:  Requests should be blocked   Then with the syntax of redirection, the page will jump to the login page   Make the program flow 

     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. Determine whether the user is logged in    Check cookie If there is a value 
        String ticket = CookieUtil.getCookieValue(request,"JT_TICKET");
        //2. check ticket
        if(!StringUtils.isEmpty(ticket)){
            //3. Judge redis Is there any value in .
            if(jedisCluster.exists(ticket)){
                //4. Get dynamic json Information 
                String userJSON = jedisCluster.get(ticket);
                User user = ObjectMapperUtil.toObj(userJSON,User.class);
                request.setAttribute("JT_USER",user);
                return true;
            }
        }
        response.sendRedirect("/user/login.html");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // Destroy data 
        request.removeAttribute("JT_USER");
    }
}` 


2.2.4 Get dynamic UserId

 Insert picture description here

2.3 ThreadLocal Introduce

2.3.1 ThreadLocal effect

name : Local thread variables
effect : Can be in the same thread , Realize the sharing of data .
 Insert picture description here

2.3.2 ThreadLocal Introductory cases

 `private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    public void a(){
        int a = 100;
        threadLocal.set(a);
        b();
    }

    public void b(){
        int a = threadLocal.get();
        int b  = 100*a;
    }` 


2.3.3 edit ThreadLocal Tools API

`public class UserThreadLocal {

    //static It doesn't affect threads   threadLocal When a thread is created, it follows .
    //private static ThreadLocal<Map<k,v>> threadLocal = new ThreadLocal<>();
    private static ThreadLocal<User> threadLocal = new ThreadLocal<>();

    public static void set(User user){

        threadLocal.set(user);
    }

    public static User get(){

        return threadLocal.get();
    }

    public static void remove(){

        threadLocal.remove();
    }

}` 


2.3.4 restructure User Interceptor

 Insert picture description here

2.3.5 Get dynamic UserId

 Insert picture description here

3. Jingtao order module

3.1 Order form design

 Insert picture description here

3.2 Create order items

3.2.1 Create project

 Insert picture description here

3.2.2 Add inheritance dependency

 `<!--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.2.3 add to POJO

 Insert picture description here
Delete orderItem The primary key ID of
 Insert picture description here

3.2.4 structure jt-order project

The order item code structure is as follows
 Insert picture description here

3.3 Order confirmation page jumps to

3.3.1 url analysis

 Insert picture description here

3.3.2 edit OrderController

`package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;
import com.jt.service.DubboOrderService;
import com.jt.thread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Reference(timeout = 3000,check = false)
    private DubboOrderService orderService;
    @Reference(timeout = 3000,check = false)
    private DubboCartService cartService;

    /**
     *  Order page Jump 
     * url: http://www.jt.com/order/create.html
     *  Page value : ${carts}
     */
    @RequestMapping("/create")
    public String create(Model model){

        //1. according to userId Query shopping cart information 
        Long userId = UserThreadLocal.get().getId();
        List<Cart> cartList = cartService.findCartListByUserId(userId);
        model.addAttribute("carts",cartList);
        return "order-cart";
    }
}` 

3.3.3 edit OrderService

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


3.3.4 Page effect display

 Insert picture description here

3.4 About SpringMVC Parameter submission problem description

3.4.1 Simple parameter transfer problem

1. page url identification

2.Controller The method in
public void xxx(String name,int age){

`}` 



3.4.2 Use object methods to receive parameters

1. page url identification
2.Controller The method in
public void xxx(User user){

`}
public class User{
    private Integer name;
    private String age;
}` 

3.4.3 Use the object's reference to assign values to parameters

difficulty : Attribute's duplicate name submission problem …
Solutions : You can assign values to properties in the form of object references .

`<input  name="name"   value=" Erlang God "    />
<input  name="age"   value="3000"    />
<input  name="dog.name"   value=" Wheezing dog "    />
<input  name="dog.age"   value="8000"    />` 

2.Controller The method in

`public void  xxx(User user){
    
    }
    public class Dog{
        private String name;
        private Integer age;    
    }
    public class User{
        private String name;
        private Integer age;    
        private Dog dog;
    }` 

3.5 About order submission

3.5.1 page URL explain

 Insert picture description here

3.5.2 Request parameters

 Insert picture description here

3.5.3 page JS analysis

`jQuery.ajax( {
            type : "POST",
            dataType : "json",
            url : "/order/submit",
            data : $("#orderForm").serialize(),
            // data: {"key":"value","key2":"value2".....}
            // data:  id=1&name="xxx"&age=18......
            cache : false,
            success : function(result) {
                if(result.status == 200){
                    location.href = "/order/success.html?id="+result.data;
                }else{
                    $("#submit_message").html(" Order submission failed , Please try again later ...").show();
                }
            },
            error : function(error) {
                $("#submit_message").html(" Dear users, please do not click frequently ,  Please try again later ...").show();
            }
        });` 


3.5.3 edit OrderController

 `/**
     *  Order submission 
     * url: http://www.jt.com/order/submit
     *  Parameters :  Whole form Forms 
     *  Return value : SysResult object     Carry return value orderId
     *  Business description :
     *    When the order is put into storage , Need to return orderId. Let the user query .
     */
    @RequestMapping("/submit")
    @ResponseBody
    public SysResult saveOrder(Order order){
        Long userId = UserThreadLocal.get().getId();
        order.setUserId(userId);
        String orderId = orderService.saveOrder(order);
        if(StringUtils.isEmpty(orderId))
            return SysResult.fail();
        else
            return SysResult.success(orderId);

    }` 

3.5.4 edit OrderService

`@Service(timeout = 3000)
public class DubboOrderServiceImpl implements DubboOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderShippingMapper orderShippingMapper;

    /**
     * Order{order The order itself /order Logistics information /order Commodity information }
     *  difficulty :   operation 3 Tables complete the warehousing operation 
     *  Primary key information : orderId
     * @param order
     * @return
     */
    @Override
    public String saveOrder(Order order) {
        //1. Splicing OrderId
        String orderId =
                "" + order.getUserId() + System.currentTimeMillis();
        //2. Complete the order warehousing 
        order.setOrderId(orderId).setStatus(1);
        orderMapper.insert(order);

        //3. Complete the order logistics warehousing 
        OrderShipping orderShipping = order.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShippingMapper.insert(orderShipping);

        //4. Complete the order goods warehousing 
        List<OrderItem> orderItems = order.getOrderItems();
        // Bulk warehousing   sql: insert into xxx(xxx,xx,xx)values (xx,xx,xx),(xx,xx,xx)....
        for (OrderItem orderItem : orderItems){
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
        }
        System.out.println(" The order has been put into storage successfully !!!!");
        return orderId;
    }
}` 

3.6 Order successfully transferred

3.6.1 page url analysis

 Insert picture description here

3.6.2 edit OrderController

 `/**
     *  Realize commodity query 
     * 1.url Address : http://www.jt.com/order/success.html?id=71603356409924
     * 2. Parameter description : id  The order no. 
     * 3. return type : success.html
     * 4. Page value method : ${order.orderId}
     */
    @RequestMapping("/success")
    public String findOrderById(String id,Model model){
        Order order = orderService.findOrderById(id);
        model.addAttribute("order",order);
        return "success";
    }` 


3.6.2 edit OrderService

 `@Override
    public Order findOrderById(String id) {
        //1. Query order information 
        Order order  = orderMapper.selectById(id);
        //2. Query order logistics information 
        OrderShipping orderShipping = orderShippingMapper.selectById(id);
        //3. Query order line item 
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",id);
        List<OrderItem> lists =orderItemMapper.selectList(queryWrapper);
        return order.setOrderItems(lists).setOrderShipping(orderShipping);
    }` 

3.6.3 Page effect display

 Insert picture description here

4 Project structure chart

 Insert picture description here

版权声明
本文为[Half bump]所创,转载请带上原文链接,感谢