Article Directory
Listener & Filter
Listener
Monitor
- You can do anything?
Monitor the occurrence of certain events. Change of state.
- Internal mechanisms listener
In fact, the interface is a callback.
#### Callback Interface
- demand:
In the execution cycle A, when the cycle time to 5, notification B.
Prior to the first pass an object A, when A 5 is performed through the object to invoke the method B. Note, however, examples of B is not transmitted directly, but pass an instance of an interface in the past.
Web listeners
A total of eight is divided into three types
- Define a class that implements the interface
- Register | configure the Listener in the web.xml project <listener>
Monitor three scopes are created and destroyed
- request —HttpServletRequest
- session —HttpSession
- application — ServletContext
ServletRequestListener
- Monitor events
request创建:
访问服务器上的任意资源都会有请求出现。
访问 html: 会
访问 jsp: 会
访问 servlet : 会
request销毁:
服务器已经对这次请求作出了响应。
- Implementation Example
- New Java class that implements the interface ServletRequestListener
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("request请求结束");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("request请求开始");
}
}
- Registered listeners in the web.xml
<listener>
<listener-class>com.lanou3g.demo.RequestListener</listener-class>
</listener>
HttpSessionListener
- Monitor events
session的创建
只要调用getSession
html: 不会
jsp: 会 getSession();
servlet: 会
session的销毁
超时 30分钟
非正常关闭 销毁
正常关闭服务器(序列化)
- Scenarios
The number of online statistics.
- Implementation Example
- New Java class that implements the interface HttpSessionListener
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionLinsener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("session被创建了");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("session销毁了");
}
}
- Registered listeners in the web.xml
<listener>
<listener-class>com.lanou3g.demo.SessionLinsener</listener-class>
</listener>
ServletContextListener
- Monitor events
- ServletContext created: when to start the server
- ServletContext destruction: Turn off the server to remove items from the server.
- Scenarios
When servletcontext created,
- I want to complete initialization
- Perform a custom task scheduling. To perform a certain task. Timer
- Implementation Example
New Java class that implements the interface ServletContextListener
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContext初始化");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContext销毁");
}
}
Registered listeners in the web.xml
<listener>
<listener-class>com.lanou3g.demo.ContextListener</listener-class>
</listener>
Monitor three scopes property status changes
Adding value can listen in scope | replace | removal action.
- servletContext — ServletContextAttributeListener
- request — ServletRequestAttributeListener
- session — HttpSessionAttributeListener
Listening httpSession which kept the value of the status change
This type of listener without registration.
- HttpSessionBindingListener
Listener with a session binding and unbinding actions
// 让javaBean 实现该接口即可
public class MySessionBindingListener implements HttpSessionBindingListener{
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("对象被绑定进来了");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("对象被解除绑定");
}
}
- HttpSessionActivationListener
Current value for monitoring session is passivated (serialization) or activation (deserialize) an operation
- Passivation (serialization)
Storing the data in memory to the hard disk
- Activating (deserialization)
Reading the data in the hard disk into memory.
- session passivation activated the intention
The session may be a lot of value, and we have a long period of time without using the value of this memory, consider the value of the session can be stored on the hard disk [passive], when the inferior one in use in the the hard disk extracted. 【activation】
- How to make passivation session within a certain time.
Configuration can be done
1. 在tomcat里面 conf/context.xml 里面配置
对所有的运行在这个服务器的项目生效
2. 在conf/Catalina/localhost/context.xml 配置
对 localhost生效。 localhost:8080
3. 在自己的web工程项目中的 META-INF/context.xml
只对当前的工程生效。
maxIdleSwap : 1分钟不用就钝化
directory : 钝化后的那个文件存放的目录位置。
D:\tomcat\apache-tomcat-7.0.52\work\Catalina\localhost\ListenerDemo\itheima
<Context>
<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
<Store className="org.apache.catalina.session.FileStore" directory="itheima"/>
</Manager>
</Context>
Filter
Filter, filtering is actually sent to the requesting client. Browser issue, and then send the servlet server processing. You can filter in the middle, in fact, play a filter role is to intercept.
-
effect
- For some sensitive words filtered
- Unified set of coding
- automatic log-in
…
How to Use Filter
- Define a class that implements Filter
public class FilterDemo implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("来到过虑器了。。。");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
- Sign filter
In the web.xml which is registered with the way the servlet basically the same.
<filter>
<display-name>FilterDemo</display-name>
<filter-name>FilterDemo</filter-name>
<filter-class>com.itheima.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In Servlet3.0 in notes can be configured by @WebFilter
Filter life cycle
- create
Created at server startup time.
- destroy
Server stops.
Filter execution order
- The client makes a request, go through the filter, if the filter is released, then get to the servlet
- If there are multiple filters, then they will come to line up according to the mapping order of registration. As long as there is a filter, does not release, then the back of the queue, and the filter will not receive our servlet request.
Filter details:
- Parameters FilterConfig init method can be used to obtain filter name registration and initialization parameters. In fact, the original intention of the design and ServletConfig here is the same.
- If you want to release, then the operation in which doFilter method, using parameters chain
chain.doFilter(request, response); 放行, 让请求到达下一个目标。
-
/ * Servlet written format and the same.
-
Match the full path begins with /
/LoginServlet
-
In order to match the directory / * start to end
/ Demo01 / *
-
* Suffix name matches begin at the end of the extension
*.jsp *.html *.do
-
-
Set against dispatcher
REQUEST: as long as the request is over, are intercepted, the default is REQUEST
the FORWARD: As long as forwards are blocked.
ERROR: page fault occurs Jump
INCLUDE: when the page that contains the intercept on.
Case I automatically log
- demand analysis
- Users log on once after normal, as long as the session does not fail, users can directly access other pages of the site, without having to log in again.
- If not logged in or failure of the session, direct access to other pages that redirect to the login page
Setting up an environment
- Build a database
- Build page
2. Some background code
Login servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String autoLogin = request.getParameter("auto_login");
UserBean user = new UserBean();
user.setUsername(userName);
user.setPassword(password);
UserDao dao = new UserDaoImpl();
UserBean userBean = dao.login(user);
if(userBean != null){
//成功了,进入首页
request.getSession().setAttribute("userBean", userBean);
response.sendRedirect("index.jsp");
}else{
//不成功...
request.getRequestDispatcher("login.jsp").forward(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Filter Code
- Realization of ideas
- First determine whether the session is valid, if the failure, redirect the request directly to the login page, allowing users to complete manually log
- If the session has not failed, then get the user login information from the session and the database to do comparison, if the right can log normal. Otherwise the redirection to the login page, allowing users to log in manually.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession();
// 如果session里没有登录信息,无法自动登录,重定向到登录页,让用户手动登录
if(session.getAttribute("username") == null) {
resp.sendRedirect("login.jsp");
return;
}
String username = (String) session.getAttribute("username");
String password = (String) session.getAttribute("password");
// 检查session中的登录信息是否正确
if(checkValid(username, password)) {
chain.doFilter(request, response);
}
}
to sum up
Listener
8个
三种类型
针对三个作用域的创建和销毁
针对三个作用域的值改变 【添加 | 替换 | 移除】
针对session中的值 【钝化 活化】 , 【绑定 解绑】
钝化 ( 序列化 )
内存中的对象存储到硬盘
超时失效。 session销毁了。
非正常关闭服务器, 钝化 。 正常关闭服务器 销毁
设置了session,多久时间。 context.xml
活化 (反序列化)
从硬盘里面读取到内存
Scenario:
ServletContextListner: When an application is deployed, server load this project, do some initialization, task scheduling.
HttpSessionListener: count the number of online
HttpSessionActivationListener: passive activation treatment
Filter
Use higher frequencies
- If a write filter.
- Define a class that implements the interface Filter
- Registration web.xml. Similar to the servlet.
- Filter release.
chain.doFilter(request, response);
-
Filter life cycle
Create an instance of the server loads the project when: Create
Destruction: Shut down the server or when removing items from the server.