java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot 图书管理系统

SpringBoot 图书管理系统(删除、强制登录、更新图书)详细代码

作者:昭著

在企业开发中,通常不采用delete语句进行物理删除,而是使用逻辑删除,逻辑删除通过修改标识字段来表示数据已被删除,方便数据恢复,本文给大家介绍SpringBoot 图书管理系统实例代码,感兴趣的朋友跟随小编一起看看吧

一、删除图书

1.并不使用delete语句:

2.以使用delete把数据删掉

3.删除图书功能的实现方法:因为我们此处我们使用逻辑删除,所以没必要搞一个deleteBook,沿用修改图书的接口updateBook即可
4.代码:由于后端代码updateBook已经实现了,所以此处只要写前端代码即可(把id传过去,status固定为0)

function deleteBook(bookId){
    var isDelete = confirm("确认删除?");
    if (isDelete){
        $.ajax({
            type: "post",
            url: "/book/updateBook",
            data: {
                id: bookId,
                status: 0  //接口设计中,0表示被删除的
            },
            success: function (result){
                if (result == ""){
                    location = "book_list.html";
                }else{
                    alert(result);
                }
            }
        });
    }
}

二、批量删除

1.思路解析:因为我们使用了逻辑删除,所以批量删除就等于批量更新,但我们不能像删除单个图书一样,使用updateBook,因为此处我们需要更新多个,updateBook只能更新一个

2.后端代码
Controller 层

@RequestMapping("/batchDelete")
public String batchDeleteBook(@RequestParam List<Integer> ids){
    log.info("接收到的ids:{}", ids);
    Integer res = bookService.batchDeleteBook(ids);
    if (res <= 0){
        log.error("批量删除失败,ids:{}", ids);
        return "失败";
    }
    return "";
}

Service 层

public Integer batchDeleteBook(@RequestParam List<Integer> ids){
    Integer res = null;
    try{
        res = bookInfoMapper.batchDelete(ids);
    }catch (Exception e){
        log.error("批量删除失败, ids:{}", ids);
    }
    return res;
}

Mapper 层

Integer batchDelete(List<Integer> ids);
<update id="batchDelete">
    update book_info
    set status = 0
    where id in
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</update>

3.前端代码

function batchDelete(){
    var isDelete = confirm("确认批量删除?");
    if (isDelete){
        var ids = [];
        $("input:checkbox[name='selectBook']:checked").each(function (){
            ids.push($(this).val());
        })
        $.ajax({
            type: "post",
            url: "/book/batchDelete?ids=" + ids,
            success:function (result){
                if (result == ""){
                    location.href = "book_list.html";
                }else{
                    alert(result);
                }
            }
        });
    }
}

三、强制登录

3.1 不使用拦截器

@Data
public class PageResult<T> {
    private List<BookInfo> records;
    private Integer total;
    //此处设置0表示成功,-1为失败
    private Integer code;
    //错误信息
    private String errMsg;
    private PageRequest request;
    public PageResult(List<BookInfo> records, Integer total, PageRequest request) {
        this.records = records;
        this.total = total;
        this.request = request;
    }
}

3.新增Result类

public enum ResultCode {
    SUCCESS(0),
    FAIL(-1),
    UNLOGIN(-2);
    private int code;
    ResultCode(int code) {
        this.code = code;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
}

4.提取Session

提取成构造函数:

优化tip:使用泛型Result<>

@Data
public class Result<T> {
    /**
     * 业务状态码
     */
    private ResultCode code;
    /**
     * 错误信息
     */
    private String errMsg;
    /**
     * 把所有的返回数据都塞到这里
     */
    private T data;
    /**
     * 成功时执行的方法
     * @return
     */
    public static <T> Result<T> seccess(Object data){
        Result result = new Result();
        result.setCode(ResultCode.SUCCESS);
        result.setErrMsg("");
        result.setData(data);
        return result;
    }
    /**
     * 失败时执行的方法
     * 有错误,无数据
     * @param errMsg
     * @return
     */
    public static <T> Result<T> fail(String errMsg){
        Result result = new Result();
        result.setCode(ResultCode.FAIL);
        result.setErrMsg(errMsg);
        result.setData(null);
        return result;
    }
    /**
     * 失败时执行的方法
     * 有错误,有
     * @param data
     * @param errMsg
     * @return
     */
    public static <T> Result<T> fail(Object data, String errMsg){
        Result result = new Result();
        result.setCode(ResultCode.FAIL);
        result.setErrMsg(errMsg);
        result.setData(data);
        return result;
    }
    /**
     * 未登录时执行的方法
     * @return
     */
    public static <T> Result<T> unlogin(){
        Result result = new Result();
        result.setCode(ResultCode.UNLOGIN);
        result.setErrMsg("用户未登录");
        result.setData(null);
        return result;
    }
}

测试

3.2 使用拦截器

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("用户登录校验开始");
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constants.SESSION_USER_KEY) != null){
            UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
            if (userInfo != null && userInfo.getId() > 0){
                return true;
            }
        }
        response.setStatus(401);
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标方法执行后");
    }
}
@Configuration
public class webConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login");  //在执行登录操作时,不要拦截
    }
}

4. 前端代码

如果前端出现了错误,可以一行行注掉代码后,通过console.log打印日志来判断错误在哪

//http连接失败时执行的方法
error: function (error) {
    console.log(error);
    if (error.status == 401) {
        console.log("401");
        location.href = "login.html";
    }
}

四、更新图书

后端代码
Controller层

@RequestMapping("/updateBook")
public String updateBook(BookInfo bookInfo){
    log.info("接收到的bookInfo:{}", bookInfo);
    Integer result = bookService.updateBook(bookInfo);
    if (result == 0){
        log.error("更新图书失败,请联系管理员");
        return "失败";
    }
    return "";
}

Service层

public Integer updateBook(BookInfo bookInfo){
    Integer res = 0;
    try{
        res = bookInfoMapper.updateBook(bookInfo);
    }catch (Exception e){
        log.error("更新图书失败,e:{}", e);
    }
    return res;
}

Mapper层

<?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.example.book_test.Mapper.BookInfoMapper">
    <update id="updateBook">
        update book_info
        <set>
            <if test="bookName != null">
                book_name = #{bookName},
            </if>
            <if test="author != null">
                author = #{author},
            </if>
            <if test="count != null">
                count = #{count},
            </if>
            <if test="price != null">
                price = #{price},
            </if>
            <if test="publish != null">
                publish = #{publish},
            </if>
            <if test="status != null">
                status = #{status}
            </if>
        </set>
        where id = #{id};
    </update>
</mapper>

前端代码

<script>
    $.ajax({
        type: "get",
        url: "/book/queryBookInfoById" + location.search,
        success: function (book){
            if (book != null) {
                //页面输入框的填充
                $("#bookId").val(book.id);
                $("#bookName").val(book.bookName);
                $("#bookAuthor").val(book.author);
                $("#bookStock").val(book.count);
                $("#bookPrice").val(book.price);
                $("#bookPublisher").val(book.publish);
                $("#bookStatus").val(book.status)
            } else {
                alert("图书不存在")
            }
        }
    });
    function update() {
        $.ajax({
            type: "post",
            url: "/book/updateBook",
            data: $("#updateBook").serialize(),
            success: function (result) {
                if (result != null) {
                    location.href = "book_list.html";
                } else {
                    alert(result);
                }
            }
        });
    }
</script>

到此这篇关于SpringBoot 图书管理系统(删除、强制登录、更新图书)详细代码的文章就介绍到这了,更多相关SpringBoot 图书管理系统内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文