欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSM整合案例-书籍管理

程序员文章站 2024-02-29 10:12:22
...

1.功能接受及页面效果展示

这是SSM整合的案例,可以对书籍进行增删改查的管理,优化了分页查询和模糊查询,配置拦截器对未登陆的用户进行拦截转到登录页面。前端的代码在我的个人博客中(点击进入)

1.1欢迎页

SSM整合案例-书籍管理

1.2 登录页

SSM整合案例-书籍管理

1.3 书籍展示页

SSM整合案例-书籍管理

1.4 新增书籍表单页

SSM整合案例-书籍管理

1.5 修改书籍表单页

SSM整合案例-书籍管理

2.dao层

目录结构:
SSM整合案例-书籍管理

BookMapper

import com.lysong.pojo.Books;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

public interface BookMapper {
    //增加一本书
    int addBook(Books books);

    //删除一本书
    int deleteBookById(int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(int id);

    //查询全部的书
    List<Books> queryAllBook(@Param(value = "curPage")int curPage,@Param(value = "pageSize")int pageSize);

    //根据书名查书
    List<Books> queryBookByName(@Param(value = "bookName")String bookName,@Param(value = "curPage")int curPage,@Param(value = "pageSize")int pageSize);

    //查询总数
    int queryBookCount();

    //查询书名的总数
    int queryBookCountByName(@Param(value = "bookName")String bookName);



}

BookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lysong.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName, bookCounts, detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookID}
    </delete>

    <update id="updateBook" parameterType="Books">
        update ssmbuild.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID = #{bookID}
    </update>
    
    <select id="queryBookById" resultType="Books">
        select * from ssmbuild.books
        where bookID=#{bookID}
    </select>
    <select id="queryBookCount"  resultType="int">
        select count(*) from ssmbuild.books;
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books limit #{curPage},#{pageSize};
    </select>

    <select id="queryBookByName"  resultType="Books">
        select * from ssmbuild.books
        <where>
            <if test="bookName != null and bookName != ''">
                bookName like #{bookName}
            </if>
        </where>
        limit #{curPage},#{pageSize};
    </select>

    <select id="queryBookCountByName"  resultType="int">
        select count(*) from ssmbuild.books
         where bookName like #{bookName};
    </select>
</mapper>

UserMapper

import com.lysong.pojo.User;

public interface UserMapper {
    User queryUser(User user);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lysong.dao.UserMapper">
    <select id="queryUser" resultType="User">
      select * from ssmbuild.user where username=#{userName} and password=#{password}
    </select>
</mapper>
在这里插入代码片

3.Service层

这里没有贴接口的代码

UserServiceImpl


import com.lysong.dao.UserMapper;
import com.lysong.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    public User queryUser(User user) {
        return userMapper.queryUser(user);
    }
}

BookServiceImpl

这里的查找方法对传过来的页码值进行了简单的逻辑判断,解决了页码可能会越界的问题

import com.lysong.dao.BookMapper;
import com.lysong.dto.PaginationDTO;
import com.lysong.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookServiceImpl implements BookService{

    @Autowired
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    @Transactional
    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }

    @Transactional
    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    @Transactional
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public PaginationDTO queryAllBook(Integer curPage, Integer pageSize) {
        PaginationDTO<Object> paginationDTO = new PaginationDTO<>();
        Integer totalPage;
        Integer totalCount = bookMapper.queryBookCount();
        if(totalCount % pageSize == 0){
            totalPage = totalCount / pageSize;
        }else {
            totalPage = totalCount / pageSize + 1;
        }
        if (curPage < 1){
            curPage = 1;
        }
        if (curPage > totalPage){
            curPage = totalPage;
        }

        paginationDTO.setPagination(totalPage,curPage);
        Integer offset = pageSize * (curPage - 1);

        List<Books> books = bookMapper.queryAllBook(offset, pageSize);
        paginationDTO.setData(books);

        return paginationDTO;
    }

    public int queryBookCountByName(String bookName) {
        return bookMapper.queryBookCountByName(bookName);
    }

    public PaginationDTO queryBookByName(String bookName,Integer curPage, Integer pageSize) {
        PaginationDTO<Object> paginationDTO = new PaginationDTO<>();
        Integer totalPage;
        Integer totalCount = bookMapper.queryBookCountByName(bookName);
        if (totalCount.equals(0)) {
            return paginationDTO;
        }
        if(totalCount % pageSize == 0){
            totalPage = totalCount / pageSize;
        }else {
            totalPage = totalCount / pageSize + 1;
        }
        if (curPage < 1){
            curPage = 1;
        }
        if (curPage > totalPage){
            curPage = totalPage;
        }

        paginationDTO.setPagination(totalPage,curPage);
        Integer offset = pageSize * (curPage - 1);

        List<Books> books = bookMapper.queryBookByName(bookName,offset,pageSize);
        paginationDTO.setData(books);

        return paginationDTO;

    }
}

4.Controller层

LoginController

import com.lysong.pojo.User;
import com.lysong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.SessionFlashMapManager;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/goLogin")
    public String goLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String Login(String username,String password,RedirectAttributes redirectAttributes, HttpSession session){
        User user = new User(username,password);
        if(userService.queryUser(user) != null){
            user.setPassword("");
            session.setAttribute("username",user.getUserName());
            return "redirect:/book/allBook";
        }else {
            redirectAttributes.addFlashAttribute("msg","用户名或密码错误");
            return "redirect:/goLogin";
        }
    }
}

BookController

import com.lysong.dto.PaginationDTO;
import com.lysong.pojo.Books;
import com.lysong.service.BookService;
import com.sun.xml.internal.ws.server.provider.SyncProviderInvokerTube;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;



    @RequestMapping("/allBook")
    public String list(Model model,
                       @RequestParam(name="curPage",defaultValue = "1") Integer curPage,
                       @RequestParam(name = "pageSize",defaultValue = "5")Integer pageSize){
        PaginationDTO paginationDTO = bookService.queryAllBook(curPage,pageSize);
        model.addAttribute("list",paginationDTO);
        return "allBook";

    }
    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println(books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdate/{id}")
    public String toUpdatePaper(@PathVariable int id, Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("book",books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println(books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable int id){
        int i = bookService.deleteBookById(id);
        System.out.println(i);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/queryBookByName")
    public String queryBookByName(@RequestParam(name = "bookName",required = false)String bookName,
                                  @RequestParam(name="curPage",defaultValue = "1") Integer curPage,
                                  @RequestParam(name = "pageSize",defaultValue = "5")Integer pageSize,
                                  Model model){
        int count = bookService.queryBookCountByName(bookName);
        if (count == 0){
            model.addAttribute("error","未查到相关书籍");
            model.addAttribute("list",null);
            return "allBook";
        }
        PaginationDTO paginationDTO = bookService.queryBookByName(bookName, curPage, pageSize);
        model.addAttribute("list",paginationDTO);
        return "allBook";
    }

}

interceptor拦截器

xml配置

<!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.lysong.controller" />
    <mvc:interceptors>
        <mvc:interceptor>
            <!--包括这个请求下面的所有-->
            <mvc:mapping path="/book/*"/>
            <bean class="com.lysong.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

LoginInterceptor

实现对是否有登陆的校验

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        //放行判断
        if(session.getAttribute("username") != null){
            return true;
        }
        if(request.getRequestURI().contains("goLogin")){
            return true;
        }
        session.setAttribute("msg","请先登录");
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false;
    }
}

相关标签: Spring全家桶