java web(SSM框架)實現部落格的上一篇、下一篇功能

zhaomaoer發表於2016-06-05

運用了mybatis
1、Service層

 public Blog getAfterBlog(Integer blogId) {
        BlogExample blogExample = new BlogExample();
        BlogExample.Criteria criteria = blogExample.createCriteria();
        criteria.andBlogIdGreaterThan(blogId);
        Blog blog = new Blog();
        if(blogMapper.selectByExample(blogExample).size() > 0 ){
            blog = blogMapper.selectByExample(blogExample).get(0);
        }else{
            blog.setTitle("這是最後一篇文章");
            blog.setBlogId(blogId);
        }
        return blog;
    }

2、Service層

@Override
    public Blog getPreBlog(Integer blogId) {
        BlogExample blogExample = new BlogExample();
        BlogExample.Criteria criteria = blogExample.createCriteria();
        criteria.andBlogIdLessThan(blogId);
        Blog blog = new Blog();
        if(blogMapper.selectByExample(blogExample).size() > 0 ){
            blog = blogMapper.selectByExample(blogExample).get(0);
        }else{
            blog.setTitle("這是第一篇文章");
            blog.setBlogId(blogId);
        }
        return blog;
    }

3、Controller層

@RequestMapping(value="/view")
    public ModelAndView viewBlog(@RequestParam("blogId") Integer blogId){
//        log.debug("In viewBlog, blogID={}", blogId);
        Blog blog = blogServiceImpl.getBlogById(blogId);
        Blog blogPre = blogServiceImpl.getPreBlog(blogId);
        Blog blogAfter = blogServiceImpl.getAfterBlog(blogId);
        ModelAndView mav = new ModelAndView("blog_view");
        mav.addObject("blog",blog);
        mav.addObject("blogPre",blogPre);
        mav.addObject("blogAfter",blogAfter);
        return mav;

    }

4、前端

<div class="last-next">
            <div>
                <a href="${pageContext.request.contextPath}/blog/view?blogId=${blogPre.blogId}" title="上一篇">
                    <i class="icon-double-angle-left"></i>${blogPre.title}
                </a>
            </div>
            <div>
                <a href="${pageContext.request.contextPath}/blog/view?blogId=${blogAfter.blogId}" title="下一篇">
                    <i class="icon-double-angle-right"></i>${blogAfter.title}
                </a>
            </div>
        </div>

相關文章