栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 电商项目

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 电商项目

                                    

前言

一、视频查询

1.准备项目前工作

2.配置mybatis 链接数据库

3.创建实体类 entity包下

4.分别创建Controller层,mapper层,service层,分别创建其实现类和接口

5.在Controller包下创建VideoController类

6.在service层中编写VideoContorller实现方法

7.在mapper层中编写VideoController查询对接数据库的接口

8.创建ViodeServiceMapper.xml配置文件

二、开发注册,登录,用户信息查询功能。

1.在request包下创建LoginRequest类

2.在Util包下创建CommenUtils工具类 用于MD5加密

3.在Util包下创建JWTUtils工具类 用于安全认证 ,令牌等用户信息安全问题

4.开发拦截器

5.创建UserController 编写注册,登录,用户信息查询功能。

三,开发自定义异常,用户下单,下单后的章节信息

1.自定义异常的开发

2.用户下单,下单后的章节信息的开发

四.pom.xml配置

五.JDBC配置

六.目录

总结


前言

使用工具idea编写接口 使用postman进行调试工作

此项目 运用技术 mysql, mybatis, spring,javese,maven 等技术编写接口 


一、视频查询

1.准备项目前工作

导入相对应的数据库

2.配置mybatis 链接数据库
server.port=8181



spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/online_xdclass?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

#开启控制台 打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#下划线转驼峰配置
mybatis.configuration.map-underscore-to-camel-case=true

#配置xml的结果别名
mybatis.type-aliases-package=com.xdclass.project.pojo.entity


mybatis.mapper-locations=classpath:mapper
    Video findDetailById(int videoId);
}

VideoServiceImpl

package com.xdclass.project.service.Impl;

import com.xdclass.project.mapper.VideoMapper;
import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoBanner;
import com.xdclass.project.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;

    public List

7.在mapper层中编写VideoController查询对接数据库的接口
package com.xdclass.project.mapper;

import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoBanner;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface VideoMapper {
    List

8.创建ViodeServiceMapper.xml配置文件




    select * from video

    
   SELECT
 v.id ,v.title,v.summary,v.cover_img,v.price,v.point,v.create_time,
c.id AS chapter_id ,c.title AS chapter_title ,c.ordered AS chapter_ordered ,
c.create_time AS chapter_create_time,
e.id AS episode_id,e.title AS episode_title ,e.num ,
e.ordered AS episode_ordered, e.create_time AS episode_create_time,
e.free,e.play_url
FROM video v
LEFT JOIN chapter c ON v.id=c.video_id
LEFT JOIN episode e ON c.id=e.chapter_id
WHERe v.id=#{video_id}
ORDER BY c.ordered,e.num ASC
    



二、开发注册,登录,用户信息查询功能。

1.在request包下创建LoginRequest类
package com.xdclass.project.pojo.request;


import lombok.*;

@Data

@AllArgsConstructor
@NoArgsConstructor
@ToString
public class LoginRequest {
    private String phone ;
    private String pwd ;
}

2.在Util包下创建CommenUtils工具类 用于MD5加密
package com.xdclass.project.Util;

import java.security.MessageDigest;

public class CommentUtils {
    public static String MD5(String data) {
        try {
            java.security.MessageDigest md =
                    MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) |
                        0x100).substring(1, 3));
            }
            return sb.toString().toUpperCase();
        } catch (Exception exception) {
        }
        return null;
    }

}

3.在Util包下创建JWTUtils工具类 用于安全认证 ,令牌等用户信息安全问题
package com.xdclass.project.Util;

import com.xdclass.project.pojo.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTUtils {

    private static final long ExPIAE = 6000 * 60 * 60 * 24 * 7;

    private static final String SECRET = "project.net1688";

    private static final String TOKEN_PREFIX = "china";


    private static final String SUBJECT = "xdclass";

    public static String geneJsonWebToken(User user) {
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("id", user.getId())
                .claim("name", user.getName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + ExPIAE))
                .signWith(SignatureAlgorithm.HS384, SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    public static Claims checkJwT(String token) {

        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        } catch (Exception e) {
            return null;
        }


    }

}

4.开发拦截器

配置拦截器的拦截路径 创建InterceptorConfig

package com.xdclass.project.config;

import com.xdclass.project.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {



    @Bean
    LoginInterceptor loginInterceptor(){
        return  new LoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor()).addPathPatterns("/api/v1/pri**")
                .excludePathPatterns("/api/v1/pri/user/Login","/api/v1/pri/user/register");

        WebMvcConfigurer.super.addInterceptors(registry);
    }
}

开发登录拦截器 

package com.xdclass.project.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdclass.project.Util.JWTUtils;
import com.xdclass.project.Util.JsonData;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {


    public static void sendJsonMassage(HttpServletResponse response, Object obj) {

        try {
            ObjectMapper jsons = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsons.writeValueAsString(obj));
            writer.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionToken = request.getHeader("token");
        if (sessionToken == null) {
            request.getParameter("token");
        }
        if (StringUtils.isNoneBlank(sessionToken)) {
            Claims claims = JWTUtils.checkJwT(sessionToken);
            if (claims == null) {

                sendJsonMassage(response, JsonData.buildError("登录过期,重新登陆"));
            }
            Integer id = (Integer) claims.get("id");
            String name = (String) claims.get("name");
            request.setAttribute("user_id", id);
            request.setAttribute("name", name);

            return true;
        }


        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

5.创建UserController 编写注册,登录,用户信息查询功能。
package com.xdclass.project.controller;


import com.xdclass.project.Util.JsonData;
import com.xdclass.project.pojo.entity.User;
import com.xdclass.project.pojo.request.LoginRequest;
import com.xdclass.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("api/v1/pri/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public JsonData register(@RequestBody Map userinfo){

        int rows = userService.save(userinfo);
        return  rows == 1?JsonData.buildSuccess():JsonData.buildError("注册失败");

    }
    @RequestMapping("Login")
    public JsonData login(@RequestBody LoginRequest loginRequest){
        String token = userService.findByPhone(loginRequest.getPhone(),loginRequest.getPwd() );
        return token == null?JsonData.buildError("登录失败"):JsonData.buildSuccess(token);
    }


    @GetMapping("find_by_token")
    public  JsonData findInfoByToken(HttpServletRequest request){
         int  userId  =  (Integer) request.getAttribute("user_id");
       User user = userService.findInfoBytoken(userId);
         if (user ==null){
             return JsonData.buildError("查询失败");
         }
        return JsonData.buildSuccess(user);
    }




}

UserService

package com.xdclass.project.service;

import com.xdclass.project.pojo.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.Map;

public interface UserService {
    int save(Map userinfo);

    String findByPhone(String phone,  String pwd);

    User findInfoBytoken(int userId);
}

 UserServiceImpl

package com.xdclass.project.service.Impl;

import com.xdclass.project.Util.CommentUtils;
import com.xdclass.project.Util.JWTUtils;
import com.xdclass.project.mapper.UserMapper;
import com.xdclass.project.pojo.entity.User;
import com.xdclass.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    //随机头像
    private static final String[] headImg = {
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"
    };
    @Autowired
    private UserMapper userMapper;

    private String getRandomImg() {
        int size = headImg.length;
        Random random = new Random();
        int index = random.nextInt(size);
        return headImg[index];
    }

   

    @Override
    public String findByPhone(String phone, String pwd) {
        User user = userMapper.findByPhone(phone, CommentUtils.MD5(pwd));
        if (user != null) {
            String token = JWTUtils.geneJsonWebToken(user);
            return token;

        } else {
            return null;

        }
    }

    @Override
    public User findInfoBytoken(int userId) {
        User user = userMapper.findInfoBytoken(userId);
        user.setPwd("");
        return user;
    }
    
    //用户注册
    public int save(Map userinfo) {
        User user1 = userMapper.findPhone("phone"); //在数据库中查找是否有相同的手机号
        if (user1 != null) {
            User user = ToUser(userinfo);
            return userMapper.save(user);
        }
        return -1;
    }
    //获取用户的信息 
    private User ToUser(Map userinfo) {
        if (userinfo.containsKey("phone")
                && userinfo.containsKey("pwd")
                && userinfo.containsKey("name")
        ) {
            User user = new User();
            user.setPhone(userinfo.get("phone"));
            user.setName(userinfo.get("name"));
            user.setCreateTime(new Date());
            user.setHeadImg("");
            String pwd = userinfo.get("pwd");
            user.setPwd(CommentUtils.MD5(pwd));
            return user;
        } else {
            return null;
        }
    }


}

UserMapper

package com.xdclass.project.mapper;

import com.xdclass.project.pojo.entity.User;
import org.apache.ibatis.annotations.Param;


public interface UserMapper {
    int save(User user);

    User findByPhone(@Param("phone") String phone, @Param("pwd") String pwd);

    User findPhone(@Param("phone") String phone);




    User findInfoBytoken(@Param("user_id") Integer userId);
}

UserMapper.xml




    
insert into user (name,pwd,head_img,phone,create_time)
        value (#{name,jdbcType=VARCHAR},#{pwd,jdbcType=VARCHAR},
        #{headImg,jdbcType=VARCHAR},#{phone,jdbcType=VARCHAR},
        #{createTime,jdbcType=TIMESTAMP})

    
        select * from  user  where  phone= #{phone}
    
    
    select * from episode where video_id =#{video_id} and  num =1
 

 PlayRecordMapper.xml




    
        insert  into play_record(user_id,video_id,current_num,episode_id,create_time)
        value (#{userId},#{valueId},#{currentNum},#{episodeId},#{createTime});
    

VideoOrderMapper.xml





    
        select * from video_order where  user_id=#{user_id} order by create_time  desc
    

四.pom.xml配置


    4.0.0
    com.xdclass
    project
    0.0.1-SNAPSHOT
    project
    Demo project for Spring Boot

    
        1.8
        UTF-8
        UTF-8
        2.3.7.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        

        
            mysql
            mysql-connector-java

        
        
            org.apache.commons
            commons-lang3
            3.9
        
        
            org.projectlombok
            lombok
            1.16.10
        

        
            com.google.guava
            guava
            19.0
        
        
            io.jsonwebtoken
            jjwt
            0.7.0
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-dependencies
                ${spring-boot.version}
                pom
                import
            
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.8.1
                
                    1.8
                    1.8
                    UTF-8
                
            
            
                org.springframework.boot
                spring-boot-maven-plugin
                2.3.7.RELEASE
                
                    com.xdclass.project.ProjectApplication
                
                
                    
                        repackage
                        
                            repackage
                        
                    
                
            
        
    


五.JDBC配置
server.port=8181



spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/online_xdclass?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

#开启控制台 打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#下划线转驼峰配置
mybatis.configuration.map-underscore-to-camel-case=true

#配置xml的结果别名
mybatis.type-aliases-package=com.xdclass.project.pojo.entity


mybatis.mapper-locations=classpath:mapper/*xml

六.目录

 总结

此项目是后端开发在开发项目中用到的技术Mysql, JavaSE,Maven,Spring,Mybatis,SpringBoot,还有一些工具类,用到Idea 软件开发 ,PostMan软件进行调试。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/889045.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号