JAVAWEB开发之分页显示、批量删除、条件查询 以及Listener监听器

来源:互联网 发布:matlab矩阵求交集 编辑:程序博客网 时间:2024/05/17 04:53

customer信息操作

 添加 批量删除 简单条件查询 分页显示

(1)添加操作

  问题:id是varchar类型,如何获取?
         使用UUID工具类获取
完成添加操作
 1.在showCustomer.jsp页面上添加一个连接,可以直接访问到添加页面 add.jsp 
2.创建add.jsp
2.1.关于生日的日历组件
2.2.1.导入js
                   <script language="javascript" type="text/javascript"             src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>
2.2.2.在input type=text组件上添加  class,onclick.
客户生日:<input type="text" name="birthday" class="Wdate" onclick="WdatePicker()"   readonly="readonly"><br>
2.2.关于id问题
使用UUID获取
3.创建CustomerAddServlet完成添加操作
3.1.得到所有请求参数封装到Customer对象
注意:1.编码问题
3.1.2.我们使用BeanUtils,注意Date类型转换问题
3.1.3.要手动封装id.
3.2.调用service完成添加操作

(2)批量删除

1.页面上怎样将数据提交到服务器端.
1.1.可以创建一个表单,将表单数据提交就可以。
1.2.直接使用js操作
需要手动拼接出url路径
2.在服务器端怎样批量删除.
2.1.得到所有要删除的id值
request.getParameterValues("ck");
2.2.在dao中使用QueryRunner的batch方法
batch(sql,Object[][]);
注意:参数二维数据,它代表的是每一条sql的参数。
{1,2,3}----->{{1},{2},{3}}

(3)简单条件查询

1.页面完成
   在showCustomer.jsp页面上完成
<div align="center">
<form>
<select name="s">
<option>请选择条件</option>
<option value="name">按姓名查询</option>
<option value="cellphone">按手机号查询</option>
<option value="description">按描述查询</option>
</select>
<input type="text" name="msg">
<input type="submit" value="查询">
</form>
</div>
问题: select的名称叫什么?每一个option的值是什么?
select可以任意起名.
option的value名称需要与customer表中的字段名称对应.
2.创建CustomerSimpleSelectServlet完成条件查询
注意sql语句问题:  String sql="select * from customer where "+field+" like ?";

(4)分页查询

问题:什么是分页,为什么使用分页?
分页就是将数据以多页去展示,使用分页可以提高客户的感受。
分页分类:
     1.物理分页
   只从数据库中查询出当前页的数据。
   优点:不占用很多内存
   缺点:效率比较低
     2.逻辑分页
   从数据库中将所有记录查询出业,存储到内存中,要想展示当前页
   数据,直接从内存中获取。
   优点:效率高
   缺点:占用内存比较高
在java开发领域,我们使用的比较多的是物理分页。
    物理分页的实现:
1.直接使用jdbc完成
使用滚动结果集.  优点:跨数据库。缺点:性能低。
2.使用数据库本身提供的分页操作.
会使用每一个数据库特定的分页函数,优点:性能高  缺点:不能跨数据库。
mysql:limit
sqlservlet:top
oracle:rownum
介绍limit使用.
select * from 表 limit m,n;
m:代表的是从第几条开始  注意:它是从0开始记录.
n:代表查询几条记录.
示例:分页音,每页显示6条,要查询第2页的数据.
select * from 表  limit  (页码-1)*每页条数,每页条数;
分页分析-------------------------------------------------------------------------
1.页码  默认第一页  
2.每页条数   人为定义
3.总条数   select count(*) from 表
4.总页数    总页数=总条数%每页条数==0?总条数/每页条数:总条数/每页条数+1
总页数=Math.ceil(总条数*1.0/每页条数);
5.当前页的数据  List<?>----->select * from 表  limit  (页码-1)*每页条数,每页条数;
 
分页代码实现-------------------------------------------------------------------------
  1.在success.jsp页面上
<a href="${pageContext.request.contextPath}/findAllByPage">查看所有客户信息(分页展示)</a><br>


  2.创建CustomerFindAllByPageServlet完成分页

问题:要向页面携带的数据有很多,不仅是要展示的数据,例如:页码,总页数等,都需要携带到页面上,怎样处理?
解决方案:可以创建一个分页Bean,在这个Bean中封装所有关于分页相关的数据.

  3.在showCustomerByPage.jsp页面上添加
<a href="/day20_1/findAllByPage?pageNum=1">首页</a>&nbsp;&nbsp;&nbsp;
<a href="/day20_1/findAllByPage?pageNum=${pb.pageNum-1}">上一页</a>&nbsp;&nbsp;&nbsp;
<a href="/day20_1/findAllByPage?pageNum=${pb.pageNum+1 }">下一页</a>&nbsp;&nbsp;&nbsp;
<a href="/day20_1/findAllByPage?pageNum=${pb.totalPage }">尾页</a>&nbsp;&nbsp;&nbsp;
在CustomerFindAllByPageServlet中处理请求参数 pageNum
int pageNum = 1;
String _pageNum = request.getParameter("pageNum");
if (_pageNum != null) {
pageNum = Integer.parseInt(_pageNum);
}
  问题:怎样控制上一页,下一页。
条件判断就可以解决.
<c:if test="${pb.pageNum==1}">
上一页&nbsp;&nbsp;&nbsp;
</c:if>
<c:if test="${pb.pageNum!=1}">
<a href="/day20_1/findAllByPage?pageNum=${pb.pageNum-1}">上一页</a>&nbsp;&nbsp;&nbsp;
</c:if>
<c:if test="${pb.pageNum==pb.totalPage}">
下一页&nbsp;&nbsp;&nbsp;
</c:if>
<c:if test="${pb.pageNum!=pb.totalPage}">
<a href="/day20_1/findAllByPage?pageNum=${pb.pageNum+1 }">下一页</a>&nbsp;&nbsp;&nbsp;
</c:if>
分页扩展-------------------------------------------------------------------------
1.设定每页显示条数
1.1.在showCustomerByPage.jsp页面上添加一个<select>
<select name="currentPage" onchange="changeCurrentPage(this.value);">
<option>--请选择每页条数--</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
</select>

function changeCurrentPage(value){
location.href="/day20_1/findAllByPage?currentPage="+value;
};

1.2.在首页,上一页,下一页,尾页的连接上也要添加每页显示条数。
例如:
<a href="/day20_1/findAllByPage?pageNum=1&currentPage=${pb.currentPage}">首页</a>

2.关于页码显示------------------------------------
<c:forEach begin="1" end="${pb.totalPage}" var="n" step="1">
<a href="/day20_1/findAllByPage?pageNum=${n}&currentPage=${pb.currentPage}">第${n}页        </a>&nbsp;&nbsp;
</c:forEach>
问题:如果页码比较多怎样处理?
可以限定页码数,例如:前5后4。
这样做,页面的判断条件比较多,可以使用自定义标签。
可以在自定义标签中通过java代码来解决判断操作。如果直接在页面上,使用<c:if>代码太乱。
具体项目代码如下:


c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?><c3p0-config><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql:///mydb1</property><property name="user">root</property><property name="password">root</property></default-config></c3p0-config>
gender.tld
<?xml version="1.0" encoding="UTF-8"?><taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"><tlib-version>1.0</tlib-version><short-name>my</short-name><uri>http://www.itcast.cn/tag</uri><tag><name>sex</name><!-- 标签名称 --><tag-class>cn.itcast.customer.tag.GenderTag</tag-class><!-- 标签类 --><body-content>empty</body-content><!-- 标签体中内容 --><attribute><name>gender</name> <!-- 属性名称 --><required>true</required> <!-- 属性必须有 --><rtexprvalue>true</rtexprvalue><!-- 属性值可以接收el表达式 --></attribute></tag><!-- 分页标签 --><tag><name>page</name><tag-class>cn.itcast.customer.tag.PageTag</tag-class><body-content>empty</body-content><attribute><name>pb</name><required>true</required> <!-- 属性必须有 --><rtexprvalue>true</rtexprvalue><!-- 属性值可以接收el表达式 --></attribute></tag></taglib>
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>    <servlet>    <servlet-name>CustomerFindAllServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerFindAllServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerDelByIdServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerDelByIdServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerFindByIdServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerFindByIdServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerUpdateServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerUpdateServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerAddServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerAddServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerDelSelectServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerDelSelectServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerSimpleSelectServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerSimpleSelectServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>CustomerFindAllByPageServlet</servlet-name>    <servlet-class>cn.itcast.customer.web.servlet.CustomerFindAllByPageServlet</servlet-class>  </servlet> <servlet-mapping>    <servlet-name>CustomerFindAllServlet</servlet-name>    <url-pattern>/findAll</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerDelByIdServlet</servlet-name>    <url-pattern>/delById</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerFindByIdServlet</servlet-name>    <url-pattern>/findById</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerUpdateServlet</servlet-name>    <url-pattern>/update</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerAddServlet</servlet-name>    <url-pattern>/add</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerDelSelectServlet</servlet-name>    <url-pattern>/delSelect</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerSimpleSelectServlet</servlet-name>    <url-pattern>/simpleSelect</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>CustomerFindAllByPageServlet</servlet-name>    <url-pattern>/findAllByPage</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>
DataSourceUtils.java
package cn.itcast.customer.utils;import java.sql.Connection;import java.sql.SQLException;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class DataSourceUtils {private static ComboPooledDataSource cpds = new ComboPooledDataSource();public static Connection getConnection() throws SQLException {return cpds.getConnection();}public static DataSource getDataSource() {return cpds;}}
IdUtils.java
package cn.itcast.customer.utils;import java.util.UUID;public class IdUtils {public static String getUUID(){return UUID.randomUUID().toString().replaceAll("-","");}// public static void main(String[] args) {// System.out.println(getUUID());// }}
GenderTag.java
package cn.itcast.customer.tag;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;public class GenderTag extends SimpleTagSupport {private String gender;public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}@Overridepublic void doTag() throws JspException, IOException {StringBuffer buff = new StringBuffer();if ("男".equals(gender)) {buff.append("<input type='radio' name='gender' value='男' checked='checked'>男<input type='radio' name='gender' value='女'>女<br>");} else {buff.append("<input type='radio' name='gender' value='男'>男<input type='radio' name='gender' value='女' checked='checked'>女<br>");}this.getJspContext().getOut().write(buff.toString());}}
PageTag.java
package cn.itcast.customer.tag;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;import cn.itcast.customer.domain.PageBean;public class PageTag extends SimpleTagSupport {private PageBean pb;public PageBean getPb() {return pb;}public void setPb(PageBean pb) {this.pb = pb;}@Overridepublic void doTag() throws JspException, IOException {StringBuffer buff = new StringBuffer();int totalPage = pb.getTotalPage();int pageNum = pb.getPageNum(); // 当前页码if (pageNum - 5 >= 0) {for (int i = pageNum-5; i < pageNum+4; i++) {if (i + 1 == pb.getPageNum()) {buff.append("<a href='/day20_1/findAllByPage?pageNum="+ (i + 1) + "¤tPage=" + pb.getCurrentPage()+ "'><font color='green'>" + (i + 1)+ "</font></a>  ");} else {buff.append("<a href='/day20_1/findAllByPage?pageNum="+ (i + 1) + "¤tPage=" + pb.getCurrentPage()+ "'>" + (i + 1) + "</a>  ");}}} else if (pageNum - 5 < 0) {for (int i = 0; i < pageNum; i++) {if (i + 1 == pb.getPageNum()) {buff.append("<a href='/day20_1/findAllByPage?pageNum="+ (i + 1) + "¤tPage=" + pb.getCurrentPage()+ "'><font color='green'>" + (i + 1)+ "</font></a>  ");} else {buff.append("<a href='/day20_1/findAllByPage?pageNum="+ (i + 1) + "¤tPage=" + pb.getCurrentPage()+ "'>" + (i + 1) + "</a>  ");}}for (int i = pageNum; i < (pageNum + 4); i++) {if (i + 1 == pb.getPageNum()) {buff.append("<a href='/day20_1/findAllByPage?pageNum="+ (i + 1) + "¤tPage=" + pb.getCurrentPage()+ "'><font color='green'>" + (i + 1)+ "</font></a>  ");} else {buff.append("<a href='/day20_1/findAllByPage?pageNum="+ (i + 1) + "¤tPage=" + pb.getCurrentPage()+ "'>" + (i + 1) + "</a>  ");}}}this.getJspContext().getOut().write(buff.toString());}}
Demo.java 手动添加数据
package cn.itcast.customer;import java.sql.SQLException;import javax.sql.DataSource;import org.apache.commons.dbutils.QueryRunner;import org.junit.Test;import cn.itcast.customer.utils.DataSourceUtils;import cn.itcast.customer.utils.IdUtils;public class Demo {@Testpublic void add() throws SQLException {QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());for (int i = 0; i < 100; i++) {runner.update("insert into customer(id) values(?)",IdUtils.getUUID());}}}
CustomerDao.java
package cn.itcast.customer.dao;import java.sql.SQLException;import java.util.List;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.ScalarHandler;import cn.itcast.customer.domain.Customer;import cn.itcast.customer.utils.DataSourceUtils;public class CustomerDao {// 查询所有客户public List<Customer> findAll() throws SQLException {String sql = "select * from customer";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());return runner.query(sql, new BeanListHandler<Customer>(Customer.class));}public void delById(String id) throws SQLException {String sql = "delete from customer where id=?";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());runner.update(sql, id);}public Customer findById(String id) throws SQLException {String sql = "select * from customer where id=?";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());return runner.query(sql, new BeanHandler<Customer>(Customer.class), id);}public void update(Customer c) throws SQLException {String sql = "update customer set name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=? where id=?";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());runner.update(sql, c.getName(), c.getGender(), c.getBirthday(),c.getCellphone(), c.getEmail(), c.getPreference(), c.getType(),c.getDescription(), c.getId());}public void add(Customer c) throws SQLException {String sql = "insert into customer values(?,?,?,?,?,?,?,?,?)";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());runner.update(sql, c.getId(), c.getName(), c.getGender(),c.getBirthday(), c.getCellphone(), c.getEmail(),c.getPreference(), c.getType(), c.getDescription());}public void delSelect(String[] id) throws SQLException {String sql = "delete from customer where id=?";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());Object[][] ids = new Object[id.length][1];for (int i = 0; i < id.length; i++) {ids[i][0] = id[i];}runner.batch(sql, ids);}// 条件查询// field 相当于字段名称// msg 相当于字段值public List<Customer> simpleSelect(String field, String msg)throws SQLException {String sql = "select * from customer where " + field + "  like ?";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());return runner.query(sql, new BeanListHandler<Customer>(Customer.class),"%" + msg + "%");}// pagNum 页码// currentPage 每页条数public List<Customer> findByPage(int pageNum, int currentPage)throws SQLException {String sql = "select * from customer limit ?,?";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());return runner.query(sql, new BeanListHandler<Customer>(Customer.class),(pageNum - 1) * currentPage, currentPage);}// 查询总条数public int findAllCount() throws SQLException {String sql = "select count(*)  from customer";QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());long count = (Long) runner.query(sql, new ScalarHandler());return (int) count;}}
Customer.java
package cn.itcast.customer.domain;import java.util.Date;public class Customer {// Id 编号 varchar(40)// name 客户姓名 varchar(20)// gender 性别 varchar(10)// birthday 生日 date// cellphone 手机 varchar(20)// email 电子邮件 varchar(40)// preference 客户爱好 varchar(100)// type 客户类型 varchar(40)// description 备注 varchar(255)private String id;private String name;private String gender;private Date birthday;private String cellphone;private String email;private String preference;private String type;private String description;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getCellphone() {return cellphone;}public void setCellphone(String cellphone) {this.cellphone = cellphone;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPreference() {return preference;}public void setPreference(String preference) {this.preference = preference;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "Customer [id=" + id + ", name=" + name + ", gender=" + gender+ ", birthday=" + birthday + ", cellphone=" + cellphone+ ", email=" + email + ", preference=" + preference + ", type="+ type + ", description=" + description + "]";}}
PageBean.java

package cn.itcast.customer.domain;import java.util.List;public class PageBean {private int pageNum; // 页码private int currentPage; // 每页条数private int totalPage; // 总页数private int totalCount; // 总条数private List<Customer> cs; // 每页数据public int getPageNum() {return pageNum;}public void setPageNum(int pageNum) {this.pageNum = pageNum;}public int getCurrentPage() {return currentPage;}public void setCurrentPage(int currentPage) {this.currentPage = currentPage;}public int getTotalPage() {return totalPage;}public void setTotalPage(int totalPage) {this.totalPage = totalPage;}public int getTotalCount() {return totalCount;}public void setTotalCount(int totalCount) {this.totalCount = totalCount;}public List<Customer> getCs() {return cs;}public void setCs(List<Customer> cs) {this.cs = cs;}}
CustomerService.java
package cn.itcast.customer.service;import java.sql.SQLException;import java.util.List;import cn.itcast.customer.dao.CustomerDao;import cn.itcast.customer.domain.Customer;import cn.itcast.customer.domain.PageBean;public class CustomerService {private CustomerDao dao = new CustomerDao();// 查询所有客户信息操作public List<Customer> findAll() throws SQLException {return dao.findAll();}// 根据id删除public void delById(String id) throws SQLException {dao.delById(id);}// 根据id查询public Customer findById(String id) throws SQLException {return dao.findById(id);}// 修改客户信息public void update(Customer c) throws SQLException {dao.update(c);}// 添加客户信息public void add(Customer c) throws SQLException {dao.add(c);}// 批量删除public void delSelect(String[] id) throws SQLException {dao.delSelect(id);}// 条件查询public List<Customer> simpleSelect(String field, String msg)throws SQLException {return dao.simpleSelect(field, msg);}// 分页操作// pageNum 页码// currentPage 每页条数public PageBean findByPage(int pageNum, int currentPage)throws SQLException {PageBean pb = new PageBean();List<Customer> cs = dao.findByPage(pageNum, currentPage);// 查询总条数:int totalCount = dao.findAllCount();// 得到总页数int totalPage = (int) Math.ceil(totalCount * 1.0 / currentPage);pb.setTotalCount(totalCount); // 封装总条数pb.setTotalPage(totalPage);// 封装总页数pb.setCs(cs);// 封装当前页数据.pb.setCurrentPage(currentPage); // 封装每页条数pb.setPageNum(pageNum);// 封装当前页码return pb;}}
CustomerAddServlet.java
package cn.itcast.customer.web.servlet;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.converters.DateConverter;import cn.itcast.customer.domain.Customer;import cn.itcast.customer.service.CustomerService;import cn.itcast.customer.utils.IdUtils;public class CustomerAddServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");// 1.得到所有请求参数,封装到javaBeanCustomer c = new Customer();DateConverter dc = new DateConverter(); // 这是一个日期类型转换器.dc.setPattern("yyyy-MM-dd");try {ConvertUtils.register(dc, java.util.Date.class);BeanUtils.populate(c, request.getParameterMap());} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}// 需要手动将id封装到Customer对象.c.setId(IdUtils.getUUID());// 2.调用serivce完成添加操作CustomerService service = new CustomerService();try {service.add(c);// 添加成功response.sendRedirect(request.getContextPath() + "/findAll");return;} catch (SQLException e) {e.printStackTrace();request.setAttribute("add.message", "添加客户信息失败");request.getRequestDispatcher("/add.jsp").forward(request, response);return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerDelByIdServlet.java
package cn.itcast.customer.web.servlet;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.itcast.customer.service.CustomerService;public class CustomerDelByIdServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");// 1.得到要删除的idString id = request.getParameter("id");// 2.调用service中根据id删除的方法CustomerService service = new CustomerService();try {service.delById(id);// 跳转到CustomerFindAllServlet,就是要重新查询一次response.sendRedirect(request.getContextPath() + "/findAll");return;} catch (SQLException e) {e.printStackTrace();response.getWriter().write("删除失败");return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerDelSelectServlet.java
package cn.itcast.customer.web.servlet;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.itcast.customer.service.CustomerService;public class CustomerDelSelectServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");// 1.得到所有要删除的客户的idString[] id = request.getParameterValues("ck");// 2.调用service,完成批量删除CustomerService service = new CustomerService();try {service.delSelect(id);response.sendRedirect(request.getContextPath() + "/findAll");return;} catch (SQLException e) {e.printStackTrace();response.getWriter().write("批量删除失败");return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerFindAllByPageServlet.java
package cn.itcast.customer.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 cn.itcast.customer.domain.Customer;import cn.itcast.customer.domain.PageBean;import cn.itcast.customer.service.CustomerService;public class CustomerFindAllByPageServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println(request.getRemoteAddr());// 1.默认访问第一页int pageNum = 1;String _pageNum = request.getParameter("pageNum");if (_pageNum != null) {pageNum = Integer.parseInt(_pageNum);}// 2.每页条数 人为定义int currentPage = 5;String _currentPage = request.getParameter("currentPage");if (_currentPage != null) {currentPage = Integer.parseInt(_currentPage);}// 3.调用service,完成查询当前页数据操作CustomerService service = new CustomerService();try {PageBean pb = service.findByPage(pageNum, currentPage);// 4.将数据存储到request域,请求转到到页面展示。request.setAttribute("pb", pb);request.getRequestDispatcher("/showCustomerByPage.jsp").forward(request, response);return;} catch (SQLException e) {e.printStackTrace();}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerFindAllServlet.java

package cn.itcast.customer.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 cn.itcast.customer.domain.Customer;import cn.itcast.customer.service.CustomerService;public class CustomerFindAllServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");// 调用servic中查询所有方法CustomerService service = new CustomerService();try {List<Customer> cs = service.findAll();request.setAttribute("cs", cs);request.getRequestDispatcher("/showCustomer.jsp").forward(request,response);return;} catch (SQLException e) {e.printStackTrace();response.getWriter().write("查询客户信息失败");return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerFindByIdServlet.java
package cn.itcast.customer.web.servlet;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.itcast.customer.domain.Customer;import cn.itcast.customer.service.CustomerService;public class CustomerFindByIdServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");// 1.得到要查询的idString id = request.getParameter("id");// 2.调用service中根据id查询的方法.CustomerService service = new CustomerService();try {Customer c = service.findById(id);request.setAttribute("c", c);request.getRequestDispatcher("/customerInfo.jsp").forward(request,response);return;} catch (SQLException e) {e.printStackTrace();response.getWriter().write("根据id查询失败");return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerSimpleSelectServlet.java
package cn.itcast.customer.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 cn.itcast.customer.domain.Customer;import cn.itcast.customer.service.CustomerService;public class CustomerSimpleSelectServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");// 1.得到请求参数String field = request.getParameter("field"); // 字段名称String msg = request.getParameter("msg"); // 字段值// 2.调用service完成查询操作CustomerService service = new CustomerService();try {List<Customer> cs = service.simpleSelect(field, msg);request.setAttribute("cs", cs);request.getRequestDispatcher("/showCustomer.jsp").forward(request,response);return;} catch (SQLException e) {e.printStackTrace();response.getWriter().write("条件查询失败");return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
CustomerUpdateServlet.java
package cn.itcast.customer.web.servlet;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.converters.DateConverter;import cn.itcast.customer.domain.Customer;import cn.itcast.customer.service.CustomerService;public class CustomerUpdateServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 处理请求编码,request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");// 1.得到所有请求参数 ,封装到javaBean中.Customer c = new Customer();DateConverter dc = new DateConverter(); // 这是一个日期类型转换器.dc.setPattern("yyyy-MM-dd");try {ConvertUtils.register(dc, java.util.Date.class);BeanUtils.populate(c, request.getParameterMap());} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}// 调用service中修改操作CustomerService service = new CustomerService();try {service.update(c);// 跳转到CustomerFindAllServlet,就是要重新查询一次response.sendRedirect(request.getContextPath() + "/findAll");return;} catch (SQLException e) {e.printStackTrace();response.getWriter().write("修改失败");return;}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@taglib  prefix="my" uri="http://www.itcast.cn/tag"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>    <title>My JSP 'index.jsp' starting page</title>  </head>    <body>${requestScope["add.message"]}<br><form action="${pageContext.request.contextPath}/add" method="post">客户姓名:<input type="text" name="name"><br>客户性别:<input type="radio" name="gender" value="男" checked="checked">男<input type="radio" name="gender" value="女">女<br>客户生日:<input type="text" name="birthday" class="Wdate" onclick="WdatePicker()" readonly="readonly"><br>客户电话:<input type="text" name="cellphone"><br>客户邮箱:<input type="text" name="email"><br>客户爱好:<input type="text" name="preference"><br>客户类型:<input type="text" name="type"><br>客户备注:<input type="text" name="description"><br><input type="submit" value="添加"></form>  </body></html>
customerInfo.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@taglib  prefix="my" uri="http://www.itcast.cn/tag"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>        <title>My JSP 'index.jsp' starting page</title>  </head>    <body><form action="${pageContext.request.contextPath}/update" method="post"><input type="hidden" name="id" value="${c.id}">客户姓名:<input type="text" name="name" value="${c.name}"><br>客户性别:<my:sex gender="${c.gender}"/><%--<c:if test="${c.gender=='男'}"><input type="radio" name="gender" value="男" checked="checked">男<input type="radio" name="gender" value="女">女</c:if><c:if test="${c.gender!='男'}"><input type="radio" name="gender" value="男">男<input type="radio" name="gender" value="女" checked="checked">女</c:if>--%>客户生日:<input type="text" name="birthday" value="${c.birthday}"><br>客户电话:<input type="text" name="cellphone" value="${c.cellphone}"><br>客户邮箱:<input type="text" name="email" value="${c.email}"><br>客户爱好:<input type="text" name="preference" value="${c.preference}"><br>客户类型:<input type="text" name="type" value="${c.type}"><br>客户备注:<input type="text" name="description" value="${c.description}"><br><input type="submit" value="修改"></form>  </body></html>
showCustomer.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><script type="text/javascript">function del(id) {var flag = window.confirm("确认删除吗");if (flag) {//确认删除location.href = "${pageContext.request.contextPath}/delById?id="+ id;}};function change() {//1.得到id为main的这个checkboxvar main = document.getElementById("main");var flag = main.checked;//2.得到所有name=ck的checkboxvar cks = document.getElementsByName("ck");//3.将cks中所有的checkbox的checked值设置为flagfor ( var i = 0; i < cks.length; i++) {cks[i].checked = flag;}};function sendDel(){document.getElementById("f").submit();//表单提交var cks = document.getElementsByName("ck");/*var url="${pageContext.request.contextPath}/delSelect?";for(var i=0;i<cks.length;i++){if(cks[i].checked){var id=cks[i].value;url+="id="+id+"&";}}*/};</script></head><body><c:if test="${empty cs}">无客户信息</c:if><c:if test="${not empty cs}"><div align="center"><form action="${pageContext.request.contextPath}/simpleSelect" method="post"><select name="field"><option>请选择条件</option><option value="name">按姓名查询</option><option value="cellphone">按手机号查询</option><option value="description">按描述查询</option></select><input type="text" name="msg"><input type="submit" value="查询"></form></div><br><form action="${pageContext.request.contextPath}/delSelect" method="post" id="f"><table border="1" align="center" width="85%"><tr><td><input type="checkbox" id="main" onclick="change();"></td><td>客户编号</td><td>客户姓名</td><td>客户性别</td><td>客户生日</td><td>客户电话</td><td>客户邮箱</td><td>客户爱好</td><td>客户类型</td><td>客户备注</td><td>操作</td></tr><c:forEach items="${cs}" var="c"><tr><td><input type="checkbox" value="${c.id}" name="ck"></td><td>${c.id }</td><td>${c.name}</td><td>${c.gender }</td><td>${c.birthday }</td><td>${c.cellphone }</td><td>${c.email }</td><td>${c.preference }</td><td>${c.type }</td><td>${c.description }</td><td><ahref="${pageContext.request.contextPath}/findById?id=${c.id}">编辑</a> <a href="javascript:void(0)" onclick="del('${c.id}')">删除</a></td></tr></c:forEach><tr><td colspan="10"><a href="javascript:void(0)" onclick="sendDel();">删除选中</a></td><td><a href="${pageContext.request.contextPath}/add.jsp">添加</a></td></tr></table></form></c:if></body></html>
showCustomerByPage.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@taglib prefix="my" uri="http://www.itcast.cn/tag"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><script type="text/javascript">function changeCurrentPage(value) {location.href = "/day20_1/findAllByPage?currentPage=" + value;};</script></head><body><c:if test="${empty pb.cs}">无客户信息</c:if><c:if test="${not empty pb.cs}"><table border="1" align="center" width="85%"><tr><td>客户编号</td><td>客户姓名</td><td>客户性别</td><td>客户生日</td><td>客户电话</td><td>客户邮箱</td><td>客户爱好</td><td>客户类型</td><td>客户备注</td></tr><c:forEach items="${pb.cs}" var="c"><tr><td>${c.id }</td><td>${c.name}</td><td>${c.gender }</td><td>${c.birthday }</td><td>${c.cellphone }</td><td>${c.email }</td><td>${c.preference }</td><td>${c.type }</td><td>${c.description }</td></tr></c:forEach><tr><td colspan="9" align="center"><ahref="/day20_1/findAllByPage?pageNum=1¤tPage=${pb.currentPage}">首页</a>   <c:if test="${pb.pageNum==1}">上一页   </c:if> <c:if test="${pb.pageNum!=1}"><ahref="/day20_1/findAllByPage?pageNum=${pb.pageNum-1}¤tPage=${pb.currentPage}">上一页</a>   </c:if> <c:if test="${pb.pageNum==pb.totalPage}">下一页   </c:if> <c:if test="${pb.pageNum!=pb.totalPage}"><ahref="/day20_1/findAllByPage?pageNum=${pb.pageNum+1 }¤tPage=${pb.currentPage}">下一页</a>   </c:if> <ahref="/day20_1/findAllByPage?pageNum=${pb.totalPage }¤tPage=${pb.currentPage}">尾页</a>   <select name="currentPage"onchange="changeCurrentPage(this.value);"><option>--请选择每页条数--</option><option value="5">5</option><option value="10">10</option><option value="20">20</option></select></td></tr><tr><td colspan="9" align="center"><c:forEach begin="1"end="${pb.totalPage}" var="n" step="1"><c:if test="${n==pb.pageNum}"><ahref="/day20_1/findAllByPage?pageNum=${n}¤tPage=${pb.currentPage}"><fontcolor='red'>第${n}页</font> </a>  </c:if><c:if test="${n!=pb.pageNum}"><ahref="/day20_1/findAllByPage?pageNum=${n}¤tPage=${pb.currentPage}">第${n}页</a>  </c:if></c:forEach></td></tr><tr><td colspan="9" align="center"><my:page pb="${pb}" /></td></tr></table></c:if></body></html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>        <title>My JSP 'index.jsp' starting page</title>  </head>    <body><a href="${pageContext.request.contextPath}/findAll">查看所有客户信息</a><br><a href="${pageContext.request.contextPath}/findAllByPage">查看所有客户信息(分页展示)</a><br>  </body></html>
运行结果如下:








监听器(Listener)

监听器就是一个实现特定接口的普通Java程序,这个程序专门用于监听另一个Java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将被立即执行。

概念:
1.事件  ActionEvent
2.事件源 JButton
3.监听器 ActionListener
4.注册监听 addActionListener();

Servlet监听器
(1)在Servlet规范中定义了多种类型的监听器,它们用于监听的事件源分别为ServletContext,HttpSession和ServletRequest这三个域对象。
(2)Servlet规范针对这三个对象上的操作,又把这多种类型的监听器划分为三种类型:
  • 监听三个域对象创建和销毁的事件监听器。
  • 监听域对象中属性的增加和删除的事件监听器。
  • 监听绑定到HttpSession域中的某个对象状态的事件监听器。
在JAVAWEB中Servlet规范中定义了三种技术 Servlet  Listener Filter
监听创建和销毁
  HttpServletRequest
     监听器:ServletRequestListener可以监听request对象的创建与销毁。
  HttpSession
     监听器:HttpSessionListener可以监听session对象的创建与销毁。
  ServletContext
     监听器:ServletContextListener可以监听application对象的创建与销毁。

监听WEB对象中的属性变化:
  HttpServletRequest属性变化
监听器:ServletRequestAttributeListener监听request对象的属性变化
  HttpSession属性变化
监听器:HttpSessionAttributeListener 监听session对象的属性变化
  ServletContext属性变化
监听器:ServletContextAttributeListener监听application对象的属性变化。   

监听ServletContext域对象创建和销毁

ServletContextListener接口用于监听ServletContext对象的创建与销毁事件
  • 当ServletContext对象被创建时,激发contextInitialized(ServletContextEvent sce)方法。
  • 当ServletContext对象被销毁时,激发contextDestroyed(ServletContextEvent sce)方法。
servletContext域对象何时创建和销毁:
创建:服务器启动针对每一个web应用创建servletcontext
销毁:服务器关闭前先关闭代表每一个web应用的servletContext

编写Servlet监听器

  • 和编写其它事件监听器一样,编写servlet监听器也需要实现一个特定的接口,并针对相应动作覆盖接口中的相应方法。
  • 和其它事件监听器略有不同的是,servlet监听器的注册不是直接注册在事件源上,而是由WEB容器负责注册,开发人员只需在web.xml文件中使用<listener>标签配置好监听器,web容器就会自动把监听器注册到事件源中。
  • 一个 web.xml 文件中可以配置多个 Servlet 事件监听器,web 服务器按照它们在 web.xml 文件中的注册顺序来加载和注册这些 Serlvet 事件监听器。
ServletContext的主流应用
保存全局应用数据对象
       例如:创建数据库连接池
加载框架配置文件
       Spring框架(配置文件随服务器启动加载) org.springframework.web.context.ContextLoaderListener 
实现任务调度(定时器)
      Timer
      TimerTask
代码演示:ServletContext的创建与销毁监听
package cn.itcast.web.listener.application;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class MyServletContextListener implements ServletContextListener {@Overridepublic void contextDestroyed(ServletContextEvent arg0) {System.out.println("servletContext对象销毁");}@Overridepublic void contextInitialized(ServletContextEvent arg0) {System.out.println("servletContext对象创建");}}
在web.xml中添加如下配置:
<listener><listener-class>cn.itcast.web.listener.application.MyServletContextListener</listener-class></listener>
启动服务器

关闭服务器:

监听HttpSession域对象创建和销毁

HttpSessionListener接口用于监听HttpSession的创建和销毁
  • 创建一个Session时,sessionCreated(HttpSessionEvent se) 方法将会被调用。
  • 销毁一个Session时,sessionDestroyed (HttpSessionEvent se) 方法将会被调用。
Session域对象创建和销毁的时机创建:用户第一次访问时,服务器创建session
销毁:如果用户的session 30分钟没有使用,服务器就会销毁session,我们在Tomcat的web.xml里面也可以配置session失效时间
在tomcat/conf/server.xml 添加
<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
        <Store className="org.apache.catalina.session.FileStore"/>
</Manager>
在tomcat关闭时 不保存session内容

监听HttpRequest域对象创建和销毁

ServletRequestListener 接口用于监听ServletRequest 对象的创建和销毁。
  • Request 对象被创建时,监听器的requestInitialized方法将会被调用。
  • Request对象被销毁时,监听器的requestDestroyed方法将会被调用。
(request对象,在浏览器窗口中多次刷新访问servlet,看request对象的创建和销毁,并写一个servlet,然后用sendRedirect、forward方式跳转到其它servlet,查看request对象的创建和消耗)
servletRequest域对象创建和销毁的时机:
创建:用户每一次访问,都会创建一个reqeust
销毁:当前访问结束,request对象就会销毁

监听三个域对象的属性变化

  • Servlet规范定义了监听 ServletContext, HttpSession, HttpServletRequest 这三个对象中的属性变更信息事件的监听器。
  • 这三个监听器接口分别是ServletContextAttributeListener, HttpSessionAttributeListener,ServletRequestAttributeListener
  • 这三个接口中都定义了三个方法来处理被监听对象中的属性的增加,删除和替换的事件,同一个事件在这三个接口中对应的方法名称完全相同,只是接受的参数类型不同。 

attributeAdded方法

当向被监听器对象中增加一个属性时,web容器就调用事件监听器的 attributeAdded 方法进行相应,这个方法接受一个事件类型的参数,监听器可以通过这个参数来获得正在增加属性的域对象和被保存到域中的属性对象
各个域属性监听器中的完整语法定义为:
  • public void attributeAdded(ServletContextAttributeEvent scae) 
  • public void attributeAdded (HttpSessionBindingEvent  hsbe) 
  • public void attributeAdded(ServletRequestAttributeEvent srae)

attributeRemoved 方法

当删除被监听对象中的一个属性时,web 容器调用事件监听器的这个方法进行相应
各个域属性监听器中的完整语法定义为:
  • public void attributeRemoved(ServletContextAttributeEvent scae) 
  • public void attributeRemoved (HttpSessionBindingEvent  hsbe) 
  • public void attributeRemoved (ServletRequestAttributeEvent srae)

attributeReplaced 方法

当监听器的域对象中的某个属性被替换时,web容器调用事件监听器的这个方法进行相应
各个域属性监听器中的完整语法定义为:
  • public void attributeReplaced(ServletContextAttributeEvent scae) 
  • public void attributeReplaced (HttpSessionBindingEvent  hsbe) 
  • public void attributeReplaced (ServletRequestAttributeEvent srae)

演示web中监听器的使用:

演示关于web中监听器怎样使用?
创建监听器步骤:
1.创建一个类,去实现指定的监听器接口.
2.重写接口中方法。
3.在web.xml文件中配置注册监听。

演示:
1.监听application对象的创建与销毁.
问题:application对象什么时候创建,什么时候销毁的?
application对象是服务器启动时创建,
服务器关闭时销毁。

2.监听session对象创建与销毁
问题:session对象什么时候创建,什么时候销毁?
session对象创建:
reqeust.getSession();它是用于获取session.
是否创建,分以下几种情况:
1.请求中如果没有jsessionid,那么就是创建session对象。
2.如果请求头中有jsessionid值:
1.如果在服务器端,有一个session的id值与其一样,不创建,直接使用。
2.如果在服务器端,没有这个session的id值,那么会创建。
session销毁:
1.默认超时  30分钟
2.设置session超时时间
setMaxInactiveInterval(int interval) 
3.invalidate()手动销毁.
4.关闭服务器
3.监听request对象创建与销毁
问题:request对象什么时候创建,什么时候销毁?
请求发生,request对象创建,响应产生request对象销毁。
-------------------------------------------------------------------------------------------
演示session的创建与销毁以及属性的改变添加和移除:
监听session的创建与销毁
package cn.itcast.web.listener.session;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class MySessionListener implements HttpSessionListener {@Overridepublic void sessionCreated(HttpSessionEvent arg0) { System.out.println("session对象创建了");}@Overridepublic void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("session对象销毁了");}}
监听session中属性的变化
package cn.itcast.web.listener.session;import javax.servlet.http.HttpSessionAttributeListener;import javax.servlet.http.HttpSessionBindingEvent;public class MySessionAttributeListener implements HttpSessionAttributeListener {@Overridepublic void attributeAdded(HttpSessionBindingEvent arg0) {// arg0.getSession(); 获取事件源,也就是获取session对象System.out.println(arg0.getName());System.out.println(arg0.getValue());System.out.println("向session中添加属性");}@Overridepublic void attributeRemoved(HttpSessionBindingEvent arg0) {System.out.println("从session中移除属性");}@Overridepublic void attributeReplaced(HttpSessionBindingEvent arg0) {System.out.println("将session中的属性修改");}}
注册监听:web.xml中添加
<listener><listener-class>cn.itcast.web.listener.session.MySessionListener</listener-class></listener><listener><listener-class>cn.itcast.web.listener.session.MySessionAttributeListener</listener-class></listener>

编写测试页面session.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'session.jsp' starting page</title></head><body><%session.setAttribute("sname", "svalue"); //添加session.setAttribute("sname", "sssss"); //修改session.removeAttribute("sname"); //移除session.invalidate();%></body></html>
运行项目 访问session.jsp

--------------------------------------------------------------------------------------
监听request对象的创建与销毁
package cn.itcast.web.listener.request;import javax.servlet.ServletRequestEvent;import javax.servlet.ServletRequestListener;public class MyRequestListener implements ServletRequestListener {@Overridepublic void requestDestroyed(ServletRequestEvent arg0) {System.out.println("request对象销毁");}@Overridepublic void requestInitialized(ServletRequestEvent arg0) {System.out.println("request对象创建");}}
在web.xml中添加配置
<listener><listener-class>cn.itcast.web.listener.request.MyRequestListener</listener-class></listener>

访问主页:


---------------------------------------------------------------------------------------------

Session绑定JavaBean的事件监听器

  • 保存在Session域中的对象可以有多种状态:绑定到session中;从Session域中解除绑定;随Session对象持久化到一个存储设备中(钝化); 随Session对象从一个存储设备中恢复(活化)
  • Servlet 规范中定义了两个特殊的监听器接口来帮助 JavaBean 对象了解自己在 Session 域中的这些状态:HttpSessionBindingListener接口和HttpSessionActivationListener接口 ,实现这两个接口的类不需要 web.xml 文件中进行注册

HttpSessionBindingListener接口:

  • 实现了HttpSessionBindingListener接口的 JavaBean 对象可以感知自己被绑定到 Session 中和从 Session 中删除的事件
  • 当对象被绑定到 HttpSession 对象中时,web 服务器调用该对象的  void valueBound(HttpSessionBindingEvent event) 方法
  • 当对象从 HttpSession 对象中解除绑定时,web 服务器调用该对象的 void valueUnbound(HttpSessionBindingEvent event)方法

HttpSessionActivationListener接口

  • 实现了HttpSessionActivationListener接口的 JavaBean 对象可以感知自己被活化和钝化的事件
  • 当绑定到 HttpSession 对象中的对象将要随 HttpSession 对象被钝化之前,web 服务器调用如下方法sessionWillPassivate(HttpSessionBindingEvent event) 方法
  • 当绑定到 HttpSession 对象中的对象将要随 HttpSession 对象被活化之后,web 服务器调用该对象的 void sessionDidActive(HttpSessionBindingEvent event)方法
在META-INF目录下新建一配置文件
<Context><Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1"><Store className="org.apache.catalina.session.FileStore" directory="it315"/></Manager></Context>
示例如下, 测试JavaBean绑定:

package cn.itcast.web.listener.domain;import javax.servlet.http.HttpSessionActivationListener;import javax.servlet.http.HttpSessionBindingEvent;import javax.servlet.http.HttpSessionBindingListener;import javax.servlet.http.HttpSessionEvent;public class User implements HttpSessionBindingListener,HttpSessionActivationListener {private int id;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void sessionDidActivate(HttpSessionEvent arg0) {System.out.println("活化");}@Overridepublic void sessionWillPassivate(HttpSessionEvent arg0) {System.out.println("钝化");}@Overridepublic void valueBound(HttpSessionBindingEvent arg0) {System.out.println("将user对象绑定到了session中");}@Overridepublic void valueUnbound(HttpSessionBindingEvent arg0) {System.out.println("从session中将user对象移除");}}
bean1.jsp
<%@page import="cn.itcast.web.listener.domain.User"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title></head><body><%User user = new User();user.setId(1);user.setName("tom");session.setAttribute("user", user); //绑定%></body></html>
bean2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ page import="cn.itcast.web.listener.domain.*" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title></head><body><%session.removeAttribute("user");//移除%></body></html>
bean3.jsp
<%@page import="cn.itcast.web.listener.domain.*"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title></head><body>${user.name}</body></html>

依次访问jsp  后台打印如下


监听器案例(销毁长时间不适用的Session)

功能:扫描session对象在指定时间内没有使用,人为销毁。
分析:
1.怎样知识session多长时间没有使用?
当前时间-最后使用时间(public long getLastAccessedTime())

2.什么时候开始扫描,扫描多长时间?
可以使用Timer完成

完成定时扫描session,如果超时没有使用,销毁案例:

1.要将所有的session对象得到,保存到集合中。
1.创建一个监听器 ServletContextListener,它服务器启动时,创建一个集合保存到ServletContext域。
2.创建一个监听器 HttpSessionListener,当创建一个session时,就从ServletContext域中获取集合,将session对象储存到集合中。
2.定时扫描
问题:
1.session超时,不能只销毁session,还要从集合中移除。
2.我们的操作,它是多线程的,要考虑集合的同步问题。
1.集合需要是线程安全的。
2.需要使用迭代器进行遍历。
代码如下:
MyServletContextListener.java
package cn.itcast.listener.demo;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;import java.util.Timer;import java.util.TimerTask;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.http.HttpSession;public class MyServletContextListener implements ServletContextListener {private List<HttpSession> sessions = Collections.synchronizedList(new ArrayList<HttpSession>());// 线程安全的List集合.public void contextDestroyed(ServletContextEvent sce) {}public void contextInitialized(ServletContextEvent sce) {// 这个方法执行了,就说明项目启动了.// 1.得到ServletContext对象ServletContext context = sce.getServletContext();// 2,将集合保存到context中.context.setAttribute("sessions", sessions);// 3.开始扫描Timer t = new Timer();t.schedule(new TimerTask() {@Overridepublic void run() {System.out.println("开始扫描session");// 判断session是否过期.----session如果10秒钟没有使用,将其销毁.for (Iterator<HttpSession> it = sessions.iterator(); it.hasNext();) {HttpSession session = it.next();// 判断session是否过期if (System.currentTimeMillis()- session.getLastAccessedTime() > 10000) {System.out.println(session.getId() + " 已经超时,被销毁了。");// sessions.remove(session);// 从集合中删除it.remove();session.invalidate();// 销毁session}}}}, 1000, 3000);}}
MyHttpSessionListener.java
package cn.itcast.listener.demo;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.http.HttpSession;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;//用于监听session对象创建,如果创建了,将其保存到一个集合中。public class MyHttpSessionListener implements HttpSessionListener {public void sessionCreated(HttpSessionEvent se) {// session创建了.// 1.得到sessionHttpSession session = se.getSession();// 2.将session保存到集合中.// 集合是在ServletContext中存储的,我们只需要从ServletContext中获取就可以。ServletContext context = session.getServletContext();List<HttpSession> sessions = (List<HttpSession>) context.getAttribute("sessions");sessions.add(session);System.out.println(session.getId() + " 添加到了集合");}public void sessionDestroyed(HttpSessionEvent se) {// TODO Auto-generated method stub}}
注册监听 在web.xml中添加配置
<!-- 监听器案例--><listener><listener-class>cn.itcast.listener.demo.MyServletContextListener</listener-class></listener><listener><listener-class>cn.itcast.listener.demo.MyHttpSessionListener</listener-class></listener> 

访问bean1.jsp 


0 0