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 {
@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 <= #{moneyLimit1}
</if>
<if test="moneyLimit2 != null and moneyLimit2 != ''">
and amount >= #{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 <= #{moneyLimit1}
</if>
<if test="moneyLimit2 != null and moneyLimit2 != ''">
and amount >= #{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) {
user.setNickname(nickname);
}
public void setName(String name) {
user.setName(name);
}
public void setAddress(String address) {
user.setAddress(address);
}
public void setPhone(String 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 {
String requestBody = HttpUtils.getRequestBody(request);
AdminLoginBO loginBO = gson.fromJson(requestBody, AdminLoginBO.class);
if(StringUtils.isEmpty(loginBO.getEmail()) || StringUtils.isEmpty(loginBO.getPwd())){
Result result = new Result(10000, "参数不能为空", null);
response.getWriter().println(gson.toJson(result));
return;
}
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);
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/*")
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");
String requestURI = request.getRequestURI();
String uri = requestURI.replace(request.getContextPath(), "");
if(!"/api/admin/admin/login".equals(uri)){
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/*")
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");
String requestURI = request.getRequestURI();
String uri = requestURI.replace(request.getContextPath(), "");
String method = request.getMethod();
if(!"OPTIONS".equals(method)){
if(!"/api/admin/admin/login".equals(uri)){
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/*")
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");
String requestURI = request.getRequestURI();
String uri = requestURI.replace(request.getContextPath(), "");
String method = request.getMethod();
if(!"OPTIONS".equals(method)){
if(!"/api/admin/admin/login".equals(uri)){
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/*")
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) {
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/*")
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");
String requestURI = request.getRequestURI();
String uri = requestURI.replace(request.getContextPath(), "");
String method = request.getMethod();
if(!"OPTIONS".equals(method)){
if(!"/api/admin/admin/login".equals(uri)){
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/*")
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) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
boolean result = isValidByReg(input);
System.out.println(result);
}
private static boolean isValidByReg(String input) {
return input.matches("\\d{6}");
}
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) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
boolean result = isValidByReg(input);
System.out.println(result);
}
private static boolean isValidByReg(String input) {
return input.matches("www\\.baidu\\.com");
}
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管理员登录了之后才可以操作)
|