JSP编程教程:JSP动作JAVABEAN
一、JSP动作JAVABEAN
JAVABEAN是一个封装了业务逻辑的可重用组件,包括可视化组件以及封装业务逻辑的组件。例如:分页
Model 1: JSP + JAVABEAN
Model 2: JSP + SERVLET + Service + Servlet + JSP 【MVC】
v JAVABEAN构造
1.构造对象
|
Goods g = new Goods();
2.设置属性值
|
g.setName("123");
3.获取属性值
g1.getName()
4.设置参数值
value="<%=request.getParameter("name") %>"/> value="<%=Integer.parseInt(request.getParameter("count")) %>"/>
|
5.设置生效范围
其值:page、application、request、session
作业:
1.练习课堂上的知识
2.写一个组件,用于打印对应的SQL语句中的数据。
value="select * from emp" /> <% List out.print(emps.get(0).getEname()); %> |
public class EmpJavaBean {
private IEmpDao dao = new EmpDaoImpl(); private String sql ; private List
public String getSql() { return sql; }
public void setSql(String sql) { this.sql = sql; }
public List list = dao.listTables(sql); //访问数据库 return list; }
} |
v JAVABEAN要求
1.必须得有一个无参的构造方法
2.提供属性的接口,使用set/get方法
3.最好实现序列化接口
v 分页
public class Page {
private int pageNo; // 当前第几页
private int pageSize; // 每页多少条数据
private int totalPages;// 总共多少页
private int totalResults;// 总共多少记录
private int defaultPageSize = 10;
private List> results;// 分页之后的结果
private String pageSQL = "";// 分页的SQL语句
private String sqlCount = "";// 获取总共多少条数据 private String clazz ;
private String html;
public void setClazz(String clazz) { this.clazz = clazz; }
public String getHtml() { this.html = " "
";
+ "当前第"+getPageNo() +"/"+getTotalPages() +"页 共"+getTotalResults()+"行 " + "" + "首页" + "上一页" + "下一页" + "尾页" + " return html; }
private JdbcTemplate template = new JdbcTemplate();
public int getDefaultPageSize() { return defaultPageSize; }
public Page() { super(); this.pageSize = defaultPageSize; }
public String getPageSQL() { return pageSQL; }
public void setPageSQL(String pageSQL) { this.pageSQL = pageSQL; try { IPageDao dao = (IPageDao)Class.forName(this.clazz).newInstance(); this.results = dao.listTables(pageSQL, new Integer[] { pageNo * pageSize, (pageNo - 1) * pageSize }); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public void setSqlCount(String sqlCount) { this.sqlCount = sqlCount; this.totalResults = template.queryForCount(sqlCount, null); this.totalPages = totalResults / pageSize == 0 ? 1 : (totalResults % pageSize == 0 ? totalResults / pageSize : totalResults / pageSize + 1); }
public int getPageNo() { return pageNo == 0 ? 1 : pageNo; }
public void setPageNo(int pageNo) { this.pageNo = pageNo < 1 ? 1 : (pageNo > totalPages ? totalPages : pageNo); }
public int getPageSize() { return pageSize; }
public void setPageSize(int pageSize) { this.pageSize = pageSize; }
public int getTotalPages() { return totalPages; }
public int getTotalResults() { return totalResults; }
public List> getResults() { return results; } } |
value="select count(*) from dept"/> value="dao.impl.DeptDaoImpl"/> value="select * from (select t.*,rownum rn from dept t where rownum<=?) where rn>? "/> <% List %> <%=emps.size() %> 注意JAVABEAN设置的先后顺序 |