您的位置:首页 > 编程语言 > Java开发

商城项目分解-各页面顶部元素的静态引入及导航条的异步加载

2017-12-11 13:33 519 查看
导航条{

    静态引入{

        把每个页面几乎都有的网站logo,登录/注册按钮,站内导航栏等单独写到一个jsp中,

        然后在其他页面使用<%@ include file="menu.jsp" %>标签引入指定文件中的代码.    }

    异步加载{

        1.使用jQuery的ajax向Servlet请求导航栏数据

        2.Servlet调Service调Dao层查数据库,返回一个List<Category>集合

        3.Servlet把集合通过JSONArray将数据传回前端页面

        4.前端页面遍历集合,展示数据

    }

    缓存技术{

        由于"导航栏"属于不会经常改变的数据,所以没必要每次都查数据库,

        这里使用缓存技术,正常情况下只会在第一次访问时会查数据库,之后都会直接从缓存中拿数据返回

        1.读取配置文件

        2.找到指定名称的缓存区

        3.判断缓存区中是否有之前存的数据

            如果有就直接拿出来返回

            如果没有就先查表并生成数据,然后在存到缓存区一份,返回一份

    }
}

异步加载核心代码

<%--通过js代码异步加载导航栏的数据--%>
<script type="text/javascript">
<%--在页面加载完毕后,指定里面的代码--%>
$(function () {
// 使用jQuery的ajax,post方式向Servlet请求导航栏的数据
$.post("${ pageContext.request.contextPath }/CategoryServlet", {"method": "findAll"}, function (data) {
// 遍历Servlet返回的数据
$(data).each(function (i, n) {
// 通过ID选择器找到导航栏对应的<ul>标签,往里面添加<li>标签
$("#menuID").append("<li><a href='${ pageContext.request.contextPath }/ProductServlet?cid=" + n.cid + "&method=findByCid&currPage=1'>" + n.cname + "</a></li>");
});
}, "json");
});
</script>
CategoryServlet核心代码

/**
* 查询所有分类的Servlet的执行的方法:findAll
*/
public String findAll(HttpServletRequest req,HttpServletResponse resp){
// 调用业务层:
try{
CategoryService categoryService = (CategoryService) BeanFactory.getBean("categoryService");
List<Category> list = categoryService.findAll();
// 将list转成JSON:
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
resp.getWriter().println(jsonArray.toString());
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException();
}
return null;
}

CategoryService +缓存技术核心代码
public List<Category> findAll()throws SQLException {
/*CategoryDao categoryDao = new CategoryDaoImpl();
return categoryDao.findAll();*/
/**
* 使用缓存优化程序,先从缓存中获取数据
* * 获取到:直接返回
* * 获取不到:查询数据库,将记录存入到缓存中.
*/
// 读取配置文件
CacheManager cacheManager = CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
// 从配置文件中获取名称为categoryCache缓存区
Cache cache = cacheManager.getCache("categoryCache");
// 判断缓存中是否有list集合:
Element element = cache.get("list");
List<Category> list = null;
if(element == null){
// 缓存中没有数据
CategoryDao categoryDao = (CategoryDao) BeanFactory.getBean("categoryDao");
list = categoryDao.findAll();
element = new Element("list",list);
cache.put(element);
}else{
// 缓存中已经存在数据
list = (List<Category>)element.getObjectValue();
}
return list;
}CategoryDao核心代码
public List<Category> findAll() throws SQLException {
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql = "select * from category";
List<Category> list = queryRunner.query(sql, new BeanListHandler<Category>(Category.class));
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异步 JavaWeb 商城