IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Java学习 day60_project(3) -> 正文阅读

[Java知识库]Java学习 day60_project(3)

Day4 订单管理

订单新增的入口在前台用户系统。可以先新建表,自己先预先插入几条数据。

在这里插入图片描述

修改订单的规格和数量,基本是不符合业务场景需求的。

修改订单只实现修改订单状态即可。

订单删除逻辑:可以选择物理删除(从表中实实在在删除该条记录)、或者逻辑删除(设置一个状态位,让用户觉得删除了该订单,其实只是对其不可见罢了)。

订单其实可以暴露一个人很多信息。用户行为画像、人物画像。 推荐算法。

订单表如何创建?

本商城在设计接口的时候,其实是没有购物车表,意味着加入购物车里面的商品其实是相当于在订单表中下了一个未付款的订单。

一个订单中永远只有一个商品

意味着本系统在设计订单表的时候不需要去设计订单详情页,所以,需求还简单了一些。

收货地址信息以及订单中的商品信息应该在订单表中存入完整的信息。

你在购物某商品时,使用的是某个地址,后面你把改地址给改了,那么会出现在配送过程中,突然地址发生变化的场景吗?

你在10年前买了一台iphone4,你去查看该订单,是否还在?订单里面的商品信息是否还在?通过订单进入该商品,发现商品不在了

订单其实是某个时刻行为的一个记录。618大促 买了手机,比平时贵了100块钱,活动结束之后 ,看订单,金额是多少呢?

id

nickname

receiver

address

phone

product

productId

spec

specId

number

amount

stateId

createtime

updatetime

hasComment

在这里插入图片描述


JavaBean:

对象。成员变量private、提供public的get和set方法。无参构造函数。

框架在封装数据到对象中,都会去调用无参构造函数来实例化一个对象,紧接着调用set方法来完成赋值

package com.cskaoyan.mall.controller;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.bo.OrdersByPageBO;
import com.cskaoyan.mall.model.vo.OrdersByPageVO;
import com.cskaoyan.mall.service.OrderService;
import com.cskaoyan.mall.service.OrderServiceImpl;
import com.cskaoyan.mall.utils.HttpUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/admin/order/*")
public class OrderServlet extends HttpServlet {

    private Gson gson = new Gson();

    private OrderService orderService = new OrderServiceImpl();

    //如果不晓得如何打断点,那么就在程序的入口处打断点
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace(request.getContextPath() + "/api/admin/order/", "");
        if("ordersByPage".equals(action)){
            ordersByPage(request, response);
        }
    }

    private void ordersByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        OrdersByPageBO ordersByPageBO = gson.fromJson(requestBody, OrdersByPageBO.class);
        //判断 金额上下限可以不填,但是如果填的话,那么一定要求是数字
        try {
            if(!StringUtils.isEmpty(ordersByPageBO.getMoneyLimit1())){
                Double.parseDouble(ordersByPageBO.getMoneyLimit1());
            }
            if(!StringUtils.isEmpty(ordersByPageBO.getMoneyLimit2())){
                Double.parseDouble(ordersByPageBO.getMoneyLimit2());
            }
        }catch (Exception e){
            response.getWriter().println(gson.toJson(Result.error("金额必须是数字")));
            return;
        }
        OrdersByPageVO orders = orderService.ordersByPage(ordersByPageBO);
        response.getWriter().println(gson.toJson(Result.ok(orders)));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
package com.cskaoyan.mall.service;

import com.cskaoyan.mall.dao.OrderDao;
import com.cskaoyan.mall.model.bo.OrdersByPageBO;
import com.cskaoyan.mall.model.vo.OrdersByPageInnerOrderVO;
import com.cskaoyan.mall.model.vo.OrdersByPageVO;
import com.cskaoyan.mall.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class OrderServiceImpl implements OrderService {

    //接下来需要做哪些事情?
    //1.查询当前条件下符合搜索条件的总记录数
    //2.当前页的具体条目信息
    // sqlSession.commit();  sqlSession.rollBack();
    @Override
    public OrdersByPageVO ordersByPage(OrdersByPageBO ordersByPageBO) {
        SqlSession sqlSession = MybatisUtils.openSession();
        OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
        int count = orderDao.getTotalCount(ordersByPageBO);
        List<OrdersByPageInnerOrderVO> orders = orderDao.ordersByPage(ordersByPageBO);
        sqlSession.commit();
        sqlSession.close();
        OrdersByPageVO ordersByPageVO = new OrdersByPageVO();
        ordersByPageVO.setTotal(count);
        ordersByPageVO.setOrders(orders);
        return ordersByPageVO;
    }
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cskaoyan.mall.dao.OrderDao">

    <select id="getTotalCount" parameterType="com.cskaoyan.mall.model.bo.OrdersByPageBO" resultType="java.lang.Integer">
        select count(*) from orders
        <where>
            <if test="id != null and id != ''">
                id = #{id}
            </if>
            <if test="name != null and name != ''">
                and receiver like concat("%", #{name}, "%")
            </if>
            <if test="address != null and address != ''">
                and address like concat("%", #{address}, "%")
            </if>
            <if test="moneyLimit1 != null and moneyLimit1 != ''">
                and amount &lt;= #{moneyLimit1}
            </if>
            <if test="moneyLimit2 != null and moneyLimit2 != ''">
                and amount &gt;= #{moneyLimit2}
            </if>
            <if test="state != -1">
                and stateId = #{state}
            </if>
        </where>
    </select>

    <select id="ordersByPage" parameterType="com.cskaoyan.mall.model.bo.OrdersByPageBO" resultType="com.cskaoyan.mall.model.vo.OrdersByPageInnerOrderVO">
        select id,userId,specId as goodsDetailId,product as goods,spec,number as goodsNum,amount,stateId,nickname,receiver as name, address,phone from orders
        <where>
            <if test="id != null and id != ''">
                id = #{id}
            </if>
            <if test="name != null and name != ''">
                and receiver like concat("%", #{name}, "%")
            </if>
            <if test="address != null and address != ''">
                and address like concat("%", #{address}, "%")
            </if>
            <if test="moneyLimit1 != null and moneyLimit1 != ''">
                and amount &lt;= #{moneyLimit1}
            </if>
            <if test="moneyLimit2 != null and moneyLimit2 != ''">
                and amount &gt;= #{moneyLimit2}
            </if>
            <if test="state != -1">
                and stateId = #{state}
            </if>
        </where>
        limit #{pagesize} offset ${(currentPage - 1) * pagesize}
    </select>
</mapper>
package com.cskaoyan.mall.model.bo;

public class OrdersByPageBO {

    private String address;
    private String moneyLimit2;
    private String moneyLimit1;
    private Integer pagesize;
    private String name;
    private String goods;
    private Integer state;
    private String id;
    private Integer currentPage;

    public void setAddress(String address) {
        this.address = address;
    }

    public void setMoneyLimit2(String moneyLimit2) {
        this.moneyLimit2 = moneyLimit2;
    }

    public void setMoneyLimit1(String moneyLimit1) {
        this.moneyLimit1 = moneyLimit1;
    }

    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setGoods(String goods) {
        this.goods = goods;
    }

    public void setState(int state) {
        this.state = state;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public String getAddress() {
        return address;
    }

    public String getMoneyLimit2() {
        return moneyLimit2;
    }

    public String getMoneyLimit1() {
        return moneyLimit1;
    }

    public int getPagesize() {
        return pagesize;
    }

    public String getName() {
        return name;
    }

    public String getGoods() {
        return goods;
    }

    public int getState() {
        return state;
    }

    public String getId() {
        return id;
    }

    public int getCurrentPage() {
        return currentPage;
    }
}
package com.cskaoyan.mall.model.vo;

public class OrdersByPageInnerOrderUserVO {
    private String address;
    private String phone;
    private String nickname;
    private String name;

    public void setAddress(String address) {
        this.address = address;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public String getPhone() {
        return phone;
    }

    public String getNickname() {
        return nickname;
    }

    public String getName() {
        return name;
    }
}
package com.cskaoyan.mall.model.vo;

public class OrdersByPageInnerOrderVO {

    private Double amount;
    private Integer goodsDetailId;
    private Integer stateId;
    private String goods;
    private Integer id;
    private String state;
    private Integer userId;
    private Integer goodsNum;
    private String spec;
    private OrdersByPageInnerOrderUserVO user = new OrdersByPageInnerOrderUserVO();

    private String nickname;

    private String name;

    private String address;

    private String phone;

    public void setNickname(String nickname) {
//       this.nickname = nickname;
        user.setNickname(nickname);
    }

    public void setName(String name) {
//        this.name = name;
        user.setName(name);
    }

    public void setAddress(String address) {
//        this.address = address;
        user.setAddress(address);
    }

    public void setPhone(String phone) {
//        this.phone = phone;
        user.setPhone(phone);
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public Integer getGoodsDetailId() {
        return goodsDetailId;
    }

    public void setGoodsDetailId(Integer goodsDetailId) {
        this.goodsDetailId = goodsDetailId;
    }

    public Integer getStateId() {
        return stateId;
    }

    public void setStateId(Integer stateId) {
        this.stateId = stateId;
        if(stateId == 0){
            setState("未付款");
        }else if(stateId == 1){
            setState("未发货");
        }else if(stateId == 2){
            setState("已发货");
        }else if(stateId == 3){
            setState("已到货");
        }
    }

    public String getGoods() {
        return goods;
    }

    public void setGoods(String goods) {
        this.goods = goods;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getGoodsNum() {
        return goodsNum;
    }

    public void setGoodsNum(Integer goodsNum) {
        this.goodsNum = goodsNum;
    }

    public String getSpec() {
        return spec;
    }

    public void setSpec(String spec) {
        this.spec = spec;
    }

    public OrdersByPageInnerOrderUserVO getUser() {
        return user;
    }

    public void setUser(OrdersByPageInnerOrderUserVO user) {
        this.user = user;
    }
}
package com.cskaoyan.mall.model.vo;

import java.util.List;

public class OrdersByPageVO {

    private Integer total;

    private List<OrdersByPageInnerOrderVO> orders;

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public List<OrdersByPageInnerOrderVO> getOrders() {
        return orders;
    }

    public void setOrders(List<OrdersByPageInnerOrderVO> orders) {
        this.orders = orders;
    }
}


Day5 权限管理

我们针对的主要是8084系统,也就是服务端系统的接口需要进行权限验证,只有当登录了管理员账号,才可以调用该接口,如果没有登录的情况下,是无法调用该接口的。

比如http://localhost:8084/api/admin/admin/allAdmins

如何加?

AdminSevlet中添加如下代码:

private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //请求参数位于请求体中,并且时以json字符串的形式存在
    //如何拿到请求体  为什么请求体是以inputStream的形式存在
    //因为请求体不仅可以存储文本类型的请求参数,还可以存储二进制类型数据  文件上传
    String requestBody = HttpUtils.getRequestBody(request);
    AdminLoginBO loginBO = gson.fromJson(requestBody, AdminLoginBO.class);
    //校验
    if(StringUtils.isEmpty(loginBO.getEmail()) || StringUtils.isEmpty(loginBO.getPwd())){
        // TODO
        Result result = new Result(10000, "参数不能为空", null);
        response.getWriter().println(gson.toJson(result));
        return;
    }
    //接下来应该调用模型的方法(三层架构里面的service和dao其实就是之前model的进一步解耦)
    //调用service的方法,返回结果即可
    int code = adminService.login(loginBO);
    Result result = null;
    if(code == 200){
        //登录成功
        LoginVo loginVo = new LoginVo(loginBO.getEmail(), loginBO.getEmail());
        result = new Result(0, null, loginVo);
        //写入session
        request.getSession().setAttribute("username", loginBO.getEmail());
    }else {
        //登录失败
        result = new Result(10000, "用户名、密码错误", null);
    }
    response.getWriter().println(gson.toJson(result));
}

Filter中代码:

package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/api/*")
// CorsFilter + AuthFilter
public class ApplicationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //表示哪些主机可以访问当前的系统
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        //取session
        //哪些是需要验证登录,哪些是不需要验证登录?
        String requestURI = request.getRequestURI();
        String uri = requestURI.replace(request.getContextPath(), "");
        if(!"/api/admin/admin/login".equals(uri)){
            //如果请求的地址不是/api/admin/admin/login那么表示的是需要验证登录状态
            String username = (String) request.getSession().getAttribute("username");
            if(username == null){
                //需要登录后才可以访问,但是此时没有登录
                response.getWriter().println(new Gson().toJson(Result.error("当前接口仅允许登录后才可以访问")));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

结果发现登录后依然无法访问到接口的内容?

意味着session中没有取到数据---------->猜想:session不是一个session对象?(验证)---------> 请求没有携带cookie:JSESSIONID=xxx(抓包)

网络迷踪

为什么发送请求时,没有携带cookie呢?

跨域。跨域时,默认情况下浏览器是不允许携带cookie的,如果希望浏览器能够携带cookie,则需要前端代码和服务端代码同时做一些设置修改:

前端:

针对axios-admin.js以及axios-client.js文件,新增如下代码:

axios.defaults.withCredentials = true


服务端代码做如下设置:

告诉浏览器,localhost:8085请求访问服务器的时候,是被localhost:8084(也就是我们的后端,不是后台,允许的)
任何源发起的访问请求,浏览器都会响应,但是接不接受是浏览器来做决定的,如果源请求是被服务器允许的,那浏览器就接受这个请求,否则就选择不接受,也就是出现跨域错误

response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");


此外,此时还有一些有问题

通过在filter中打log,追踪

OPTIONS /api/admin/admin/loginorg.apache.catalina.session.StandardSessionFacade@2e6e9993
POST /api/admin/admin/loginorg.apache.catalina.session.StandardSessionFacade@321d1645
login:org.apache.catalina.session.StandardSessionFacade@321d1645
login:FA9DAEDCC183E64226901B5AB194DCFB
OPTIONS /api/admin/admin/allAdminsorg.apache.catalina.session.StandardSessionFacade@38070b83
GET /api/admin/admin/allAdminsorg.apache.catalina.session.StandardSessionFacade@321d1645

每次发送OPTIONS请求时,依然会去创建一个新的session对象,发送真正的请求,是不会创建session对象的

发送OPTIONS请求时,不会携带cookie的(试探性请求,是不会携带cookie的)

发送真正的请求,携带了cookie

package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/api/*")
// CorsFilter + AuthFilter
public class ApplicationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //表示哪些主机可以访问当前的系统
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        //取session
        //哪些是需要验证登录,哪些是不需要验证登录?
        String requestURI = request.getRequestURI();
        String uri = requestURI.replace(request.getContextPath(), "");
        //System.out.println(request.getMethod() + " " + requestURI + request.getSession());
        String method = request.getMethod();
        if(!"OPTIONS".equals(method)){
            if(!"/api/admin/admin/login".equals(uri)){
                //如果请求的地址不是/api/admin/admin/login那么表示的是需要验证登录状态
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("username");
                if(username == null){
                    //需要登录后才可以访问,但是此时没有登录
                    response.getWriter().println(new Gson().toJson(Result.error("当前接口仅允许登录后才可以访问")));
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

紧接着转入前台。

转入前台之后,因为之前的filter设置的url-pattern是/api/*,意味着访问前台时,必须后台管理系统人员登录之后才可以访问到前台数据。很明显不合理。给前台单独设置一个filter。

package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/api/admin/*")
// CorsFilter + AuthFilter
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //表示哪些主机可以访问当前的系统
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        //取session
        //哪些是需要验证登录,哪些是不需要验证登录?
        String requestURI = request.getRequestURI();
        String uri = requestURI.replace(request.getContextPath(), "");
        //System.out.println(request.getMethod() + " " + requestURI + request.getSession());
        String method = request.getMethod();
        if(!"OPTIONS".equals(method)){
            if(!"/api/admin/admin/login".equals(uri)){
                //如果请求的地址不是/api/admin/admin/login那么表示的是需要验证登录状态
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("username");
                if(username == null){
                    //需要登录后才可以访问,但是此时没有登录
                    response.getWriter().println(new Gson().toJson(Result.error("当前接口仅允许登录后才可以访问")));
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

专门用来处理后台管理系统的接口

再新建一个MallFilter

package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/api/mall/*")
// CorsFilter + AuthFilter
public class MallFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //表示哪些主机可以访问当前的系统
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

处理前台的逻辑。

通过去抓包

http://localhost:8084/api/mall/index/getType

发现接口的返回值和后台管理系统的返回值是一模一样的。

新建一个新的Servlet,然后service、dao直接复用现成的即可。

package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.Type;
import com.cskaoyan.mall.service.GoodsService;
import com.cskaoyan.mall.service.GoodsServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/mall/index/*")
public class IndexServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImpl();

    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace(request.getContextPath() + "/api/mall/index/", "");
        if("getType".equals(action)){
            getType(request, response);
        }
    }

    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> type = goodsService.getType();
        response.getWriter().println(gson.toJson(Result.ok(type)));
    }
}

转入前台之后,原则:

新建servlet,但是service、dao可以直接复用,如果不能够复用,那么就创建新的方法到原先的service中、原先的dao中

比如首页获取商品信息,写到原先GoodsService中

优化点:

针对filter中设置的

? response.setHeader(“Access-Control-Allow-Origin”,“http://localhost:8085”);

public GetGoodsByTypeVO(Integer id, String name, Integer typeId, String img, Double price, Integer stockNum) {
    this.id = id;
    this.name = name;
    this.typeId = typeId;
    this.img = "http://localhost:8084/" + img;
    this.price = price;
    this.stockNum = stockNum;
}

以硬编码的形式存储下来的。

针对跨域部分的内容,需要将服务端代码改成

? response.setHeader(“Access-Control-Allow-Origin”,“http://你的ip地址:8085”);

前端代码需要修改:

axios.defaults.baseURL = ‘http://你的ip地址:8084’;

将服务端部分的地址信息以配置文件的形式配置下来。

package com.cskaoyan.mall.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebListener
public class ApplicationListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //读取properties配置文件里面的内容,然后放入context域
        InputStream inputStream = ApplicationListener.class.getClassLoader().getResourceAsStream("application.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            String origin = properties.getProperty("origin");
            servletContextEvent.getServletContext().setAttribute("origin", origin);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/api/admin/*")
// CorsFilter + AuthFilter
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //表示哪些主机可以访问当前的系统
        ServletContext servletContext = request.getServletContext();
        String origin = (String) servletContext.getAttribute("origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        //取session
        //哪些是需要验证登录,哪些是不需要验证登录?
        String requestURI = request.getRequestURI();
        String uri = requestURI.replace(request.getContextPath(), "");
        //System.out.println(request.getMethod() + " " + requestURI + request.getSession());
        String method = request.getMethod();
        if(!"OPTIONS".equals(method)){
            if(!"/api/admin/admin/login".equals(uri)){
                //如果请求的地址不是/api/admin/admin/login那么表示的是需要验证登录状态
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("username");
                if(username == null){
                    //需要登录后才可以访问,但是此时没有登录
                    response.getWriter().println(new Gson().toJson(Result.error("当前接口仅允许登录后才可以访问")));
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/api/mall/*")
// CorsFilter + AuthFilter
public class MallFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //表示哪些主机可以访问当前的系统
        ServletContext servletContext = request.getServletContext();
        String origin = (String) servletContext.getAttribute("origin");

        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}


Day6 正则表达式

package com.cskaoyan.mall;

import com.alibaba.druid.util.StringUtils;

import java.util.Scanner;

public class RegTest {

    public static void main(String[] args) {
        //判断用户输入的是否是6位数字
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        //boolean result = isValid(input);
        boolean result = isValidByReg(input);
        System.out.println(result);
    }

    private static boolean isValidByReg(String input) {
        return input.matches("\\d{6}");
    }

    /**
     * 判断用户输入的是否是6位数字
     * @param input
     * @return
     */
    private static boolean isValid(String input) {
        if(StringUtils.isEmpty(input)){
           return false;
        }
        if(input.length() != 6){
            return false;
        }
        try {
            Integer.parseInt(input);
            return true;
        }catch (Exception e){

        }
        return false;
    }
}
package com.cskaoyan.mall;

import com.alibaba.druid.util.StringUtils;

import java.util.Scanner;

public class RegTest {

    public static void main(String[] args) {
        //判断用户输入的是否是6位数字
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        //boolean result = isValid(input);
        boolean result = isValidByReg(input);
        System.out.println(result);
    }

    private static boolean isValidByReg(String input) {
        //return input.matches("\\d{6}");
        //正则表达式最简单的用法就是用来判断和给定字符一模一样的字符串
        //return input.matches("123456");
        //次数限定符只作用于最邻近的一个字符  z  zo zoo  zooooo....
//        return input.matches("zo*");
        //如果想匹配zozo,应该怎么做?
//        return input.matches("(zo)*");
//        return input.matches("go{2,}gle");
        //匹配z或者food,如果想匹配zood或者food,需要将(z|f)
//        return input.matches("z|food");
//        return input.matches("(z|f)ood");
        //1.只能匹配一位  2.这一位必须是abcd中的一个
//        return input.matches("[abcd]");
        //匹配26个字母呢
//        return input.matches("[a-z]");
        //1. 只能匹配一位  2.这一位不能是abcd中的任意一个
//        return input.matches("[^abcd]");
        // ^如果在[]里面,表示的是取反,如果不在[]里面,表示的是匹配开始的位置
//        return input.matches("^hello$");
//        return input.matches("\\d{6}");
        //想匹配一个网址  www.baidu.com
        //在正则中.表示的是匹配任意一位字符,如果想匹配.,那么需要对其进行转义  \   \\(java)
        return input.matches("www\\.baidu\\.com");
    }

    /**
     * 判断用户输入的是否是6位数字
     * @param input
     * @return
     */
    private static boolean isValid(String input) {
        if(StringUtils.isEmpty(input)){
           return false;
        }
        if(input.length() != 6){
            return false;
        }
        try {
            Integer.parseInt(input);
            return true;
        }catch (Exception e){

        }
        return false;
    }
}

前台的filter也是需要拦截一些东西的。

个人主页的信息。如果用户没有登录,那么直接访问用户的个人主页应当是不予展示的,加入购物车、下单等接口。

前台针对的是用户的操作(如果用户没有登录,那么和用户信息相关的内容应当是不能显示的)

后台针对的是admin的操作(因为后台管理系统所有的接口都必须要求admin管理员登录了之后才可以操作)

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章           查看所有文章
加:2021-10-03 16:57:32  更:2021-10-03 17:00:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 18:50:02-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码