- 上一篇是登录注册的页面,注册成功跳转到登录,登录成功跳转到首页
- 下面来实现首页的代码,先来看要实现的页面
- 要实现一个头部的head.jsp页面,
- 该页面通过<jsp:include page=“head.jsp”/>动态包含在index.jsp首页、goodsList.jsp商品展示页面中
- head.jsp实现的功能:点击登录、注册、注销按钮实现效果,(输入框、购物车代码还没实现,先给个div就行)
- 还有就是对商品类别表(type表)中的数据(1:手机,2:电脑,3:家居……)的展示,也就是商品分类,在head.jsp页面中给一个<ul id=“goodsType”></ul>标签,在<script></script>中实现,通过ajxa异步显示
$.ajax({
url:“”,
type:“”,
dataType:“”,
success:function(data){
//处理data
},
error:function(){
//报错信息
}
})
- url给地址"/type?method=findAllType",该findAllType方法就是查type表的数据,把数据转成json格式返回
- 通过导包:fastjson-1.2.jar,JSON.toJSONString(),转成json格式
- type给get/post,这里用get
- dataType给格式,上面返回的json格式,所以这里type=“json”
- success:function(data){}获取成功,查到的type表中的数据就在data数组中,
- foreach遍历data数组,data[0].tname就是调用该数组第一个对象的tname属性
- 遍历并依次创建li>a标签添加到上面定义的ul标签里面
- 通过jQuery方法添加:$(“#goodsType”).append(“<li><a></a></li>”);jQuery使用详解
- a标签的href给的是/product?method=show&tid=${data[i].tid};
- 实现的就是点击手机、电脑通过a标签的href传值,调用show方法,show方法实现的就是:根据同时传来的tid值,在商品表中查找t_id=tid的商品,例如点击手机tid=1,就是查的所有的手机,点击电脑tid=2,就是查所有电脑。
- 查到的数据,放在req.serAttribute(“pageBean”,pageBean);数据保存起来
- show方法最后的返回值就是跳转到goodsList.jsp页面
- goodsList.jsp页面通过JSTL遍历刚刚保存的pageBean什么是JSTL?
- 以上遍历获取的数据太多了,需要实现分页
- 分页:分页查询详解
- 就是查数据的时候,sql语句给个limit ?,?
- 于是定义一个PageBean<T>类,保存第几页的数据,
一、head.jsp
- 导航是从bootstrap直接复制的,也就是<nav class=“navbar navbar-default”></nav>的内容,要给a标签的路径
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<%-- <meta charset="UTF-8">--%>
<%-- <meta http-equiv="X-UA-Compatible" content="IE=edge">--%>
<%-- <meta name="viewport" content="width=device-width, initial-scale=1.0">--%>
<title>Title</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css.map">
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url: "${pageContext.request.contextPath}/type?method=findAllType",
type: "GET",
dataType: "json",
success: function (data) {
for (var i in data) {
var a = "<li><a href='${pageContext.request.contextPath}/product?method=show&tid=" + data[i].tid + "'>" + data[i].tname + "</a></li>";
$("#goodsType").append(a);
}
},
error: function () {
alert("失败");
}
})
})
</script>
</head>
<body>
<div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">myShop商城</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="${pageContext.request.contextPath}/Login.jsp">登录<span class="sr-only">(current)</span></a>
</li>
<li><a href="${pageContext.request.contextPath}/Register.jsp">注册</a></li>
<li><a href="${pageContext.request.contextPath}/user?method=loginOut">注销</a></li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="搜索一下">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">购物车</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<nav class="navbar navbar-default">
<p>
<ul id="goodsType">
</ul>
</p>
</nav>
</div>
</body>
</html>
二、Servle、Dao、Service
2.1 TypeController
- 重点就是findAllType()方法,返回的是json
- 调用service层的findAll方法,findAll()调用dao层的selectAll方法
- selectAll方法的sql语句就是““select t_id as tid,t_name as tname,t_info as tinfo from type limit 0,5;””
@WebServlet(name = "TypeController",value = "/type")
public class TypeController extends BaseServlet {
public String findAllType(HttpServletRequest request,HttpServletResponse response){
TypeService typeService = new TypeServiceImpl();
List<Type> list = typeService.findAll();
String json = JSON.toJSONString(list);
return json;
}
}
2.1.1dao层
public interface TypeDao {
public List<Type> selectAll();
}
2.1.2daoImpl
public class TypeDaoImpl implements TypeDao {
private QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
@Override
public List<Type> selectAll() {
List<Type> list = null;
String sql = "select t_id as tid,t_name as tname,t_info as tinfo from type limit 0,5;";
try {
list = queryRunner.query(sql,new BeanListHandler<Type>(Type.class));
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
2.1.3 service层
public interface TypeService {
public List<Type> findAll();
}
2.1.4 serviceImpl
public class TypeServiceImpl implements TypeService {
@Override
public List<Type> findAll() {
List<Type> list = null;
TypeDao typeDao = new TypeDaoImpl();
list = typeDao.selectAll();
return list;
}
}
2.2 ProductController
- 重点就是PageBean<T>类,要给list 、pageIndex、pageSize、totalRows参数
- 调用service层的goodsList()方法,给的参数是第几页pageIndex,页大小pageSize,tid返回结果就是PageBean<Product>
- tid就是查商品表中分类是tid的商品,这里tid=1,定义的都是手机
- goodsList()方法调用dao层的selectCountByTid(tid)方法查当前tid=1的商品有几个,返回long值,注意sql语句是“select count(1) from product where t_id = ?”
- goodsList()方法调用dao层的selectProductByPage((pageIndex-1)*pageSize, pageSize,tid) 方法查tid=tid的商品从(pageIndex-1)*pageSize行,依次再查pageSize行,返回结果是List<Product>数组
- 注意sql语句是"select p_id as pid,t_id as tid,p_name as pname,p_time as ptime,p_image as pimage,p_price as pprice,p_state as pstate,p_info as pinfo from product where t_id = ? limit ?,?;"
@WebServlet(name = "ProductController",value = "/product")
public class ProductController extends BaseServlet {
public String show(HttpServletRequest req, HttpServletResponse resp) {
int tid = Integer.parseInt(req.getParameter("tid"));
int pageSize = 8;
String pageIndex = req.getParameter("pageIndex");
int page = 1;
if(pageIndex!=null){
page = Integer.parseInt(pageIndex);
}
//调用业务逻辑获取要展示的商品列表
ProductService productService = new ProductServiceImpl();
PageBean<Product> productPageBean = productService.goodsList(page,pageSize,tid);
req.setAttribute("pageBean",productPageBean);
return Constants.FORWARD+Constants.FLAG+"/goodsList.jsp";
}
}
2.2.1 PageBean<T>
- List<T> list保存List<Product>
- int pageIndex;//定义第几页
- int pageSize; //定义页大小
- long totalRows; //全部数据有多少行
- int totalPage; //全部数据根据页大小确定多少页
- int startRow; //查询从第几行开始查,起始行
- 给上面的所有属性添加get和set方法,构造方法给前4个参数
- 给getTotalPage()方法return的值改为 return (totalRows % pageSize==0?totalRows / pageSize :pageRows /pageSize +1);
import java.util.List;
public class PageBean<T> {
private List<T> list;
private int startRow;//起始行
private long totalRows;//总行数
private int pageIndex;//页码
private int pageSize;//页大小
private int totalPage;//总页数
public PageBean(List<T> list, int pageIndex, int pageSize,long totalRows) {
this.list = list;
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.totalRows = totalRows;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public long getTotalRows() {
return totalRows;
}
public void setTotalRows(long totalRows) {
this.totalRows = totalRows;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotalPage() {
return (totalRows % pageSize == 0 ? totalRows / pageSize : totalRows / pageSize + 1);
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
}
2.2.2 dao层
public interface ProductDao {
public List<Product> selectProductByPage(int startRow,int pageSize,int type);
public long selectCountByTid(int type);
}
daoImpl
public class ProductDaoImpl implements ProductDao {
private QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
@Override
public List<Product> selectProductByPage(int startRow, int pageSize, int type) {
List<Product> list = null;
String sql = "select p_id as pid,t_id as tid,p_name as pname,p_time as ptime,p_image as pimage,p_price as pprice,p_state as pstate,p_info as pinfo from product where t_id = ? limit ?,?;";
try {
list = queryRunner.query(sql,new BeanListHandler<Product>(Product.class),type,startRow,pageSize);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
@Override
public long selectCountByTid(int type) {
Long count = null;
String sql = "select count(1) from product where t_id = ?";
try {
count= (Long) queryRunner.query(sql,new ScalarHandler(),type);
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
}
2.2.3 service层
ProductService
public interface ProductService {
public PageBean<Product> goodsList(int pageIndex, int pageSize, int type);
}
ProductServiceImpl
public class ProductServiceImpl implements ProductService {
@Override
public PageBean<Product> goodsList(int pageIndex, int pageSize, int type) {
ProductDao productDao = new ProductDaoImpl();
List<Product> list = productDao.selectProductByPage(((pageIndex-1)*pageSize),pageSize,type);
long count = productDao.selectCountByTid(type);
PageBean<Product> productPageBean = new PageBean<Product>(list,pageIndex,pageSize,count);
return productPageBean;
}
}
三、goodsList.jsp页面
- 重点就是foreach
- 上面说过了这里是处理req.setAttribute(“pageBean”,pageBean);
- jQuery方法获取${pageBean.list},这里.list是调用pageBean的getList()方法
- 获取的就是List<Product> list商品表的数据;
- JSTL方法遍历和判断,jsp页面开头加上<@taglib prefix=“c” url = “http://java.sun.com/jsp/jstl/core”%>,导包javax.servlet.jsp.jstl-api-1.2.2.jar
- 遍历:<c:foreach\ items=“${pageBean.list}” var=“g”> </c:foreach>
- 判断:<c:if test=“”></c:if>,判断是为了当再第一页和最后一页的时候不能再点击了
上面一行显示4个商品,通过class="col-xs-3"栅格实现
每个商品的框是class=“thumbnail”
框里面的文字信息class=“caption”
分页查询
具体看代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<title>Title</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css.map">
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</head>
<body>
<jsp:include page="header.jsp"/>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">商品列表</h3>
</div>
<div class="panel-body">
<c:forEach items="${pageBean.list}" var="g" varStatus="i">
<div class="col-xs-3">
<div class="thumbnail">
<img src="${pageContext.request.contextPath}/${g.pimage}" width="180" height="180" alt="">
<div class="caption">
<h4>商品名称:${g.pname}</h4>
<p>
热销指数
<c:forEach begin="1" end="${g.pstate}">
<img src="image/hot.png" width="10" height="10" alt="">
</c:forEach>
</p>
<p>上架日期:${g.ptime}</p>
<p class="text-danger">价格:${g.pprice}</p>
</div>
</div>
</div>
</c:forEach>
</div>
<div class="panel-footer">
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${pageBean.pageIndex>1}">
<li>
<a href="${pageContext.request.contextPath}/product?method=show&tid=${param.tid}&pageIndex=${pageBean.pageIndex-1}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:if test="${pageBean.pageIndex==1}">
<li>
<a aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach begin="1" end="${pageBean.totalPage}" step="1" var="index">
<li>
<a href="${pageContext.request.contextPath}/product?method=show&tid=${param.tid}&pageIndex=${index}">${index}</a>
</li>
</c:forEach>
<c:if test="${pageBean.pageIndex<pageBean.totalPage}">
<li>
<a href="${pageContext.request.contextPath}/product?method=show&tid=${param.tid}&pageIndex=${pageBean.pageIndex+1}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<c:if test="${pageBean.pageIndex==pageBean.totalPage}">
<a aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</c:if>
</ul>
</nav>
</div>
</div>
</body>
</html>