案例19-页面使用ajax显示类别菜单

1 版本一

版本只能在首页显示类别,当切换到了其它页面就不会显示

1 web层IndexServlet代码

package www.test.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import www.test.domain.Category;
import www.test.domain.Product;
import www.test.service.ProductService;

public class IndexServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ProductService service = new ProductService();
        
        //获取热门商品-----List<Product>
        List<Product> hotProductList = null;
        try {
            hotProductList = service.findHotProductList();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
        //获取最新商品-----List<Product>
        List<Product> newProductList = null;
        try {
            newProductList = service.findNewProductList();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
        //准备分类数据
        List<Category> categoryList =null;
        try {
            categoryList = service.findAllCategory();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        request.setAttribute("categoryList", categoryList);
        
        
        //将获取的数据存入request域
        request.setAttribute("hotProductList", hotProductList);
        request.setAttribute("newProductList", newProductList);
        
        //转发
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

2 service层代码

//获取商品分类
public List<Category> findAllCategory() throws SQLException {
    ProductDao dao = new ProductDao();
    List<Category> categoryList = dao.findAllCategory();
    return categoryList;
}

3 dao层代码

//获取商品分类
public List<Category> findAllCategory() throws SQLException {
    QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
    String sql = "select * from category";
    List<Category> categoryList = qr.query(sql, new BeanListHandler<Category>(Category.class));
    return categoryList;
}

4 heaher.jsp代码修改

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<!-- 登录 注册 购物车... -->
<div class="container-fluid">
    <div class="col-md-4">
        <img src="img/logo2.png"/>
    </div>

    <div class="col-md-5">
        <img src="img/header.png" />
    </div>
    <div class="col-md-3" style="padding-top:20px">
        <ol class="list-inline">
            <c:if test="${empty user }">
                <li><a href="login.jsp">登录</a></li>
                <li><a href="register.jsp">注册</a></li>
            </c:if>
            <c:if test="${!empty user }">
                <li>欢迎您,${user.username }</li>
                <li><a href="#">退出</a></li>
            </c:if>
            
            <li><a href="cart.jsp">购物车</a></li>
            <li><a href="order_list.jsp">我的订单</a></li>
        </ol>
    </div>
</div>

<!-- 导航条 -->
<div class="container-fluid">
    <nav class="navbar navbar-inverse">
        <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="#">首页</a>
            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav" id="categoryUl">
                
                    <c:forEach items="${categoryList }" var="category">
                        <li><a href="#">${category.cname }</a>
                    </c:forEach>
                    
                </ul>
                <form class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
            </div>
        </div>
    </nav>
</div>

2 版本二使用ajax显示类别菜单

版本二中可以实现所有页面的类别的动态获取.原来IndexServlet里面获取类别数据的代码不在需要了

新编写一个CategoryListServlet.

1 web层CategoryListServlet代码

package www.test.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import www.test.domain.Category;
import www.test.service.ProductService;

public class CategoryListServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ProductService service = new ProductService();

        // 准备分类数据
        List<Category> categoryList = null;
        try {
            categoryList = service.findAllCategory();
        } catch (SQLException e) {

            e.printStackTrace();
        }
        //使用转换工具将categoryList转换成json格式
        Gson gson = new Gson();
        String json = gson.toJson(categoryList);
        
        //将转换后的json格式字符串写出
          //写回前先解决乱码问题
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

service的代码和dao的代码与版本一一样

2 header.jsp代码修改

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<!-- 登录 注册 购物车... -->
<div class="container-fluid">
    <div class="col-md-4">
        <img src="img/logo2.png"/>
    </div>

    <div class="col-md-5">
        <img src="img/header.png" />
    </div>
    <div class="col-md-3" style="padding-top:20px">
        <ol class="list-inline">
            <c:if test="${empty user }">
                <li><a href="login.jsp">登录</a></li>
                <li><a href="register.jsp">注册</a></li>
            </c:if>
            <c:if test="${!empty user }">
                <li>欢迎您,${user.username }</li>
                <li><a href="#">退出</a></li>
            </c:if>
            
            <li><a href="cart.jsp">购物车</a></li>
            <li><a href="order_list.jsp">我的订单</a></li>
        </ol>
    </div>
</div>

<!-- 导航条 -->
<div class="container-fluid">
    <nav class="navbar navbar-inverse">
        <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="#">首页</a>
            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav" id="categoryUl">
                <%-- 不在需要了使用后面的ajax解决问题 --%>
                <%-- <c:forEach items="${categoryList }" var="category">
                        <li><a href="#">${category.cname }</a>
                    </c:forEach> --%>
                    
                </ul>
                <form class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
            </div>
        </div>
        
        <!-- 实现引入header.jsp页面的所有页面都动态获取类别 -->
        <script type="text/javascript">
            //header.jsp加载完毕后 去服务器端获得所有的category数据
            //引入header.jsp的页面本身已经引入的jquery文件,所以不用再次引入
            $(function(){
                var content = "";
                $.post(
                    "${pageContext.request.contextPath}/categoryList",
                    function(data){
                        //[{"cid":"xxx","cname":"xxxx"},{},{}]
                        //动态创建<li><a href="#">${category.cname }</a></li>
                        for(var i=0;i<data.length;++i){
                            content += "<li><a href='#'>"+data[i].cname+"</a></li>";
                        }
                        //将拼接好的li放置到ul中
                        $("#categoryUl").html(content);
                    },
                 "json"    
                );
            });
        </script>
        
        
    </nav>
</div>

 

posted @ 2018-02-12 11:20  Jepson6669  阅读(439)  评论(0编辑  收藏  举报