SpringBoot项目—mall商城
系统功能结构
整体思路
- 使用Spring Boot + MyBatis实现一个电商平台系统
- 使用Maven构建项目
- 使用Git做版本控制
- 前台系统
- 后台系统
前台系统
注册、登录、商品、购物车、订单
后台系统
登录、统计、商品、订单、分类、个人信息
数据库表结构
系统架构
后台系统:登录、注销
效果图:
遇到的问题:用户名失去焦点时自动显示对应的头像,应该注意,前端js使用JSON
传值:
//获取用户头像
function getUserProfilePicture(username) {
if (username !== null && username !== "") {
$.getJSON("/admin/login/profile_picture", {"username": username}, function (data) {
if (data.success) {
if (data.srcString !== null) {
$("#img_profile_picture").attr("src", "/res/images/item/adminProfilePicture/" + data.srcString);
return true;
}
}
});
}
$("#img_profile_picture").attr("src", "/res/images/admin/loginPage/default_profile_picture-128x128.png");
}
data.success
的值是一个true
或者false
的类型,如果我们没有传递一个正确的值,那么代码将一直卡在这一行。我们可以定义一个实体类:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SuccessParam {
private Boolean success;
private String srcString;
}
在控制器的代码如下:
@RequestMapping("/login/profile_picture")
@ResponseBody
public SuccessParam photo(@RequestParam("username")String name,
HttpServletRequest request,
HttpSession session){
SuccessParam successParam = new SuccessParam();
//获取图片地址
String picture = service.picture(name);
session.setAttribute("srcString",picture);
if(picture != null){
successParam.setSuccess(true);
successParam.setSrcString(picture);
return successParam;
}else {
return null;
}
}
此时,如果用户名是正确的,获取到了图片地址,我们就能给success传递true,前端就能正确响应,展示一下SQL:
@Select("SELECT adminProfilePictureSrc FROM admin WHERE adminName = #{adminName}")
public String picture(String adminName);
根据用户名查询图片地址
拦截器
拦截器用于限制用户权限。否则很有可能出现用户在没有登录的情况下修改地址栏的地址直接进入主页的情况。
编写步骤:
-
创建拦截器:
前提条件:继承
HandleInterceptor
接口public class LoginInterceptor implements HandlerInterceptor {}
实现拦截接口:
preHandle
: 作用:前置-请求进入
controller
之前 返回值:
Boolean true
:请求继续执行,false
:请求结束 写法:
判断
session
中是否存在登陆对象 根据判断结果进行处理
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("进入拦截器的路径:"+request.getRequestURI()); //判断登录-session里面是否存在登录对象 HttpSession session = request.getSession(); Admin admin = (Admin) session.getAttribute("admin"); if(admin != null){ //存在:直接放行 return true; }else{ //不存在:跳转到登录状态已失效界面 admin/include/loginMessage response.sendRedirect("/admin/loginMessage.html"); return false; } }
-
配置拦截器:
spring:dispatcher-servlet.xml
springboot
:需要使用Java配置类代替原spring的配置文件 创建一个配置类
@Configuration
指定当前类是配置类的注解 继承
WebMvcConfiguration
类配置拦截器
重写
addInterceptors
接口 添加拦截器
指定需要拦截的路径
指定不需要拦截的路径
@Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //添加拦截器 //拦截的内容 //不拦截的内容 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/admin/login.html", "/admin/login1/", "/res/**", "/admin/loginMessage.html", "/admin/login/profile_picture", "/fore/login.html"); } }