初始时为静态的效果:
它只是一个普通的下拉列表,不能执行任何操作,我接下来的是它能在每一个界面都能点击,并且动态的获取数据,因此需要在listener层添加一个监听类:
注意需要进行勾选这个:
数据库的类目:
查询类目需在dao层添加一个class,命名为:TypeDao.java
查询的SQL以及抛出异常:
package com.guiyan.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.guiyan.model.Type;
import com.guiyan.utils.DBUtil;
public class TypeDao {
public List selectAll() throws SQLException {
QueryRunner r=new QueryRunner(DBUtil.getDataSource());
String sql="select * from type";
return r.query(sql, new BeanListHandler(Type.class));
}
}
在service添加一个类,命名为:TypeService.java
packagecom.guiyan.service;importjava.sql.SQLException;importjava.util.List;importcom.guiyan.dao.TypeDao;importcom.guiyan.model.Type;public classTypeService {private TypeDao tDao=newTypeDao();public ListselectAll(){
List list=null;try{
list=tDao.selectAll();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnlist;
}
}
为了在每一个页面都能加载到,我们在ApplicationListener.java中加入:
packagecom.guiyan.listener;importjava.util.List;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;importjavax.servlet.annotation.WebListener;importcom.guiyan.model.Type;importcom.guiyan.service.TypeService;
@WebListenerpublic class ApplicationListener implementsServletContextListener {private TypeService tService=newTypeService();public voidcontextDestroyed(ServletContextEvent arg0) {
}public voidcontextInitialized(ServletContextEvent arg0) {
List list=tService.selectAll();
arg0.getServletContext().setAttribute("typeList", list);
}
}
展示需要在header.jsp中进行展示:
初始时:
1
2 pageEncoding="UTF-8"%>
3
4
5
6
7
header8
9
10
11
12
13
14
15
16
17
18 Toggle navigation
19
20
21
22
23 蛋糕店
24