15.监听器概述【理解】
疑问
-
tomcat服务器内存数据(三大域对象)发生变化了,我们能不能在内存数据改变的时候做一些业务控制?
可以,但是要使用监听器
介绍
服务器对三大域对象(request,session,servletContext)的创建与销毁,里面存储数据的增、删、改进行监听定义了监听器接口,我们可以通过实现监听器接口实现对域变化时进行业务控制。
监听器分类
ServletContextListener介绍
可以获取到上下文域对象创建与销毁的时间点进行业务控制
小结
-
监听器的作用是什么?
获取域对象改变的时间点,让我们在对应的时间点进行业务逻辑控制
16.ServletContextListener监听对象创建与销毁【应用】
疑问
-
如何知道服务器启动与销毁了?
需要实现ServletContextListener就可以获取服务器的创建与销毁。
实现步骤
- 创建一个类实现ServletContextListener接口,重写2个方法
- 配置注解将当前类交给服务器去管理
注解方式代码
package com.itheima.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/*
* servletContext对象什么时候创建?什么时候销毁?
* 答:servletContext对象是服务器启动时最早最先创建的对象,比过滤器早;服务器关闭的时候。
* */
@WebListener //注解含义:将当前监听器类交给服务器管理
public class MyServletContextListener implements ServletContextListener {
//当服务器创建servletContext上下文域对象的时候触发调用的方法
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("==servletContext对象被创建了==");
}
//当服务器销毁servletContext上下文域对象的时候触发调用的方法
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("==servletContext对象被销毁了==");
}
}
web.xml方式配置将监听器交给服务器管理
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--配置监听器-->
<listener>
<listener-class>com.itheima.listener.MyServletContextListener</listener-class>
</listener>
</web-app>
运行效果
小结
-
ServletContextListener可以获取到什么时间点?
可以获取servletContext对象创建与销毁的时间点
17.ServletContextListener的作用【应用】
作用
package com.itheima.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Timer;
import java.util.TimerTask;
/*
* servletContext对象什么时候创建?什么时候销毁?
* 答:servletContext对象是服务器启动时最早最先创建的对象,比过滤器早;服务器关闭的时候。
* */
@WebListener //注解含义:将当前监听器类交给服务器管理
public class MyServletContextListener implements ServletContextListener {
//当服务器创建servletContext上下文域对象的时候触发调用的方法
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("==servletContext对象被创建了==");
/*
* 获取到servletContext创建的时间点有什么用?ServletContextListener的作用?
* 答:我们因为上下文域对象的创建是最早的时间点,通常可以做如下2个操作:
* 1.加载自定义配置文件数据,spring框架的配置文件就是使用这个监听器进行加载的
* 2.开启定时器任务运行
* 定时器任务:按照指定的时间执行任务
* js的定时器语法:setInterval()或setTimeout()
* */
//目标:java的jdk定时器
//1.创建定时器类Timer
Timer timer = new Timer();
//2.订制定时任务计划
//方式1:timer.schedule(TimerTask,long,long);
// 参数1:TimerTask,任务接口,编写任务代码
// 参数2:long,设置距离第一次执行的毫秒数
// 参数3:long,每一次执行的间隔毫秒数
//方式2:timer.schedule(TimerTask,Date,long);
// 参数1:TimerTask,任务接口,编写任务代码
// 参数2:Date,设置第一次执行的时间
// 参数3:long,每一次执行的间隔毫秒数
/*需求:每3秒输出一次hello world*/
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello world");
}
},0,3000);
}
//当服务器销毁servletContext上下文域对象的时候触发调用的方法
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("==servletContext对象被销毁了==");
}
}
18.web项目的路径讲解【扩展】
路径配置方式有2种
1.相对路径(静态页面上推荐,因为静态页面无法动态获取部署资源目录路径):
格式:url="相对资源路径"
含义:相对于当前的静态页面的路径
例子:<form action="login" method="post"> login是相对路径
2.全路径(服务器端java代码推荐):
格式1:url="/资源路径" 服务器内部使用,当前"/"代表当前项目内
例子:request.getRequestDispatcher("/demo").forward(request,response);
格式2:url="/web项目资源部署目录名字/资源路径" 浏览器去执行,重定向和jsp使用
例子:response.sendRedirect(request.getContextPath()+"/demo");
路径演示:
19.联系人修改案例1—数据回显【扩展】
目标
实现点击修改按钮到修改页面显示修改的数据
效果
实现步骤
实现代码
IContactDao代码
//根据id查询联系人对象
@Select("SELECT * FROM contact WHERE id=#{id}")
Contact findById(int id);
ContactService代码
//根据id查询联系人对象
public Contact findById(int id){
//1.获取SqlSession连接对象
SqlSession sqlSession = MybatisUtils.getSession();
//2.dao代理对象
IContactDao contactDao = sqlSession.getMapper(IContactDao.class);
//3.调用业务根据id获取联系人对象
Contact contact = contactDao.findById(id);
//4.释放连接
MybatisUtils.closeSession(sqlSession);
//5.返回结果
return contact;
}
FindContactServlet
package com.itheima.web;
import com.itheima.entity.Contact;
import com.itheima.service.ContactService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "FindContactServlet", urlPatterns = "/FindContactServlet")
public class FindContactServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
//实例业务类
private ContactService contactService = new ContactService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求数据id
int id = Integer.parseInt(request.getParameter("id"));
//2.调用业务逻辑根据id查询联系人数据
Contact contact = contactService.findById(id);
//3.定义数组存储省份列表
String[] provinces = {"广东","湖南","福建","广西","吉林"};
//4.将上面的数据写入到请求域
request.setAttribute("contact",contact);
request.setAttribute("provinces",provinces);
//5.转发跳转update.jsp页面去显示数据
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
}
20.联系人修改案例2—更新数据到数据库【扩展】
目标
实现修改数据到数据库
效果
实现步骤
实现代码
IContactDao代码
//修改联系人信息
@Update("UPDATE contact SET sex=#{sex},age=#{age},address=#{address},qq=#{qq},email=#{email} where id=#{id}")
void update(Contact contact);
ContactService代码
//修改联系人信息
public void updateContact(Contact contact){
//1.获取SqlSession连接对象
SqlSession sqlSession = MybatisUtils.getSession();
//2.dao代理对象
IContactDao contactDao = sqlSession.getMapper(IContactDao.class);
//3.调用业务修改联系人
contactDao.update(contact);
//4.释放连接
MybatisUtils.closeSession(sqlSession);
}
UpdateContactServlet代码
package com.itheima.web;
import com.itheima.entity.Contact;
import com.itheima.service.ContactService;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "UpdateContactServlet", urlPatterns = "/UpdateContactServlet")
public class UpdateContactServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
//实例业务
private ContactService contactService = new ContactService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.获取表单数据封装到Contact对象中
Contact contact = new Contact();
BeanUtils.populate(contact,request.getParameterMap());
//2.调用业务修改数据
contactService.updateContact(contact);
//3.修改成功,提示成功再跳转到查询联系人列表Servlet
response.getWriter().write("<script>alert('修改成功');location.href='"+request.getContextPath()+"/ListContactServlet';</script>");
} catch (Exception e) {
e.printStackTrace();
//来到修改失败
//4.修改失败,返回修改页面
response.getWriter().write("<script>alert('修改失败');history.back();</script>");
}
}
}
update.jsp页面
21.删除联系人案例【扩展】
目标
实现点击删除实现删除联系人
效果
实现代码
IContactDao代码
//删除联系人
@Delete("DELETE FROM contact WHERE id=#{id}")
void delete(int id);
ContactService代码
//删除联系人
public void deleteContact(int id){
//1.获取SqlSession连接对象
SqlSession sqlSession = MybatisUtils.getSession();
//2.dao代理对象
IContactDao contactDao = sqlSession.getMapper(IContactDao.class);
//3.调用业务删除联系人
contactDao.delete(id);
//4.释放连接
MybatisUtils.closeSession(sqlSession);
}
DeleteContactServlet代码
package com.itheima.web;
import com.itheima.service.ContactService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "DeleteContactServlet", urlPatterns = "/DeleteContactServlet")
public class DeleteContactServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
//实例业务
private ContactService contactService = new ContactService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取联系人的id
int id = Integer.parseInt(request.getParameter("id"));
//2.调用业务删除
contactService.deleteContact(id);
//3.跳转到查询联系人列表servlet
response.sendRedirect(request.getContextPath()+"/ListContactServlet");
}
}
list.jsp代码
21.删除联系人案例【扩展】
目标
实现点击删除实现删除联系人
实现代码
IContactDao代码
//删除联系人
@Delete("DELETE FROM contact WHERE id=#{id}")
void delete(int id);
ContactService代码
//删除联系人
public void deleteContact(int id){
//1.获取SqlSession连接对象
SqlSession sqlSession = MybatisUtils.getSession();
//2.dao代理对象
IContactDao contactDao = sqlSession.getMapper(IContactDao.class);
//3.调用业务删除联系人
contactDao.delete(id);
//4.释放连接
MybatisUtils.closeSession(sqlSession);
}
DeleteContactServlet代码
package com.itheima.web;
import com.itheima.service.ContactService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "DeleteContactServlet", urlPatterns = "/DeleteContactServlet")
public class DeleteContactServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
//实例业务
private ContactService contactService = new ContactService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取联系人的id
int id = Integer.parseInt(request.getParameter("id"));
//2.调用业务删除
contactService.deleteContact(id);
//3.跳转到查询联系人列表servlet
response.sendRedirect(request.getContextPath()+"/ListContactServlet");
}
}