变动代码
1.controller层
@RequestMapping("/findAll.do")
public ModelAndView findAll(@RequestParam(defaultValue = "1") int currentPage) {
PageInfo<User> pageInfo=userService.findAll(currentPage);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("pageInfo",pageInfo);
modelAndView.setViewName("user-list");
return modelAndView;
}
2.service层
@Override
public PageInfo<User> findAll(int currentPage) {
PageInfo<User> pageInfo=new PageInfo<>();
pageInfo.setSize(5);
int tc= userDao.getTotalCount();
pageInfo.setTotalCount(tc);
int tp=(int)Math.ceil(tc/5.0);
pageInfo.setTotalPage(tp);
if(currentPage<1){
pageInfo.setCurrentPage(1);
}else if(currentPage>tp){
pageInfo.setCurrentPage(tp);
}else{
pageInfo.setCurrentPage(currentPage);
}
int start=(pageInfo.getCurrentPage()-1)*5;
List<User> userList = userDao.findAll(start);
pageInfo.setList(userList);
return pageInfo;
}
3.html
</div>
<!-- /.box-body -->
<div class="box-tools pull-right">
<ul class="pagination">
<li><a href="${pageContext.request.contextPath}/user/findAll.do" aria-label="Previous">首页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?currentPage=${pageInfo.currentPage-1}">上一页</a></li>
<c:forEach begin="1" end="${pageInfo.totalPage}" var="pageNum">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?currentPage=${pageNum}">${pageNum}</a></li>
</c:forEach>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?currentPage=${pageInfo.currentPage+1}">下一页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?currentPage=${pageInfo.totalPage}" aria-label="Next">尾页</a></li>
</ul>
</div>
</div>
4.登录拦截
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.zhongruan.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
import com.zhongruan.bean.User;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
HttpServletRequest request=(HttpServletRequest) servletRequest;
HttpServletResponse response=(HttpServletResponse)servletResponse;
HttpSession session=request.getSession();
User user=(User)session.getAttribute("user");
String uri=request.getRequestURI();
if(user==null && uri.indexOf("login.do")==-1){
//重定向
response.sendRedirect(request.getContextPath()+"../login.jsp");
}else{
//用来继续执行
filterChain.doFilter(request,response);
}
}
public void init(FilterConfig config) throws ServletException {
}
}