当前位置:网站首页>Filter filter details (listeners and their applications)
Filter filter details (listeners and their applications)
2022-07-25 10:10:00 【Zero degrees Celsius】
Filter Filter details
1. filter
Fillter: filter , It's used to filter the data of the website ;
- Deal with Chinese code
- validate logon …
web The service has some garbage requests , When the background should not process or should report an error, the filter will filter
2. Filter Development steps
- Guide pack
- Write filters
package com.qian.filter;
import javax.servlet.*;
import java.io.IOException;
// initialization :web Server startup , It's already initialized , Wait for the filter object to appear at any time !
// The destruction :eb When the server is down , Just destroy
public class CharacterEncodingFilter implements Filter {
//init: initialization destroy: The destruction
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter initialization ");
}
//chain: chain
/* 1. Filter all code in the , When filtering specific requests, it will execute 2. You have to keep the filter going */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=UTF-8");
System.out.println(" CharacterEncodingFilter Before execution ...");
filterChain.doFilter(servletRequest,servletResponse); // Let our request go on , If you don't write , The program is intercepted and stopped here !
System.out.println(" CharacterEncodingFilter After execution ...");
}
public void destroy() {
System.out.println("CharacterEncodingFilter The destruction ");
}
}
- stay web.xml Register filters in
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.qian.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!-- As long as it is /servlet Any request under , It goes through this filter -->
<url-pattern>/servlet/*</url-pattern> </filter-mapping> 3. Monitor
- Implement a listener interface :( There are many kinds of )
- Write a listener , Implement monitor interface
package com.qian.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
// Count the number of people online : Statistics session
public class OnlineCountListener implements HttpSessionListener {
// establish session monitor : Look at your every move
// Once created Session This event will be triggered once
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
// The destruction session monitor
// Once destroyed Seesion This event will be triggered once
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
se.getSession().invalidate();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
ctx.setAttribute("OnlineCount",onlineCount);
/* * Session The destruction : * 1. Destroy by hand :getSession().invalidate(); * * 2. Automatically destroy ---->web.xml Middle configuration * */
}
}
- web.xml Registering listener
<!-- Register listener -->
<listener>
<listener-class>com.qian.listener.OnlineCountListener</listener-class>
</listener>
<!-- session Automatically destroy -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
4. filter 、 Common applications of listeners
Monitor :GUI Programming often uses
Log in and log out
- Users can enter the home page only after logging in , Users cannot enter the home page after logging out
// Sign in
package com.qian.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get the parameters of the front-end request
String username = req.getParameter("Username");
if (username.equals("admin")){
req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
// Cancellation
package com.qian.servlet;
import com.qian.util.Constant;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
if (user_session!=null){
req.getSession().removeAttribute("USER_SESSION");
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
register
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.qian.servlet.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.qian.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.qian.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
jsp Design
<%-- Home page
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/4/11
Time: 16:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1> Login successful </h1>
<p><a href="/servlet/logout"> Cancellation </a></p>
</body>
</html>
<%-- The login page
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/4/11
Time: 16:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Sign in </title>
</head>
<body>
<h1> Sign in </h1>
<form action=${pageContext.request.contextPath}/servlet/login method="post">
<input type="text" name="username">
<input type="submit">
</form>
<%-- The login page ----> Submit a request to /servlet/login----> Operation request , Successful jump success--%>
</body>
</html>
<%-- Error page
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/4/11
Time: 20:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Login error </title>
</head>
<body>
<h1> error </h1>
<h3> No permission or wrong user name </h3>
<a href="/login.jsp"> Return to login page </a>
</body>
</html>
- When entering the home page, judge whether the user has logged in , requirement : Implement... In the filter
package com.qian.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest)servletRequest;
HttpServletResponse response1 = (HttpServletResponse)servletResponse;
Object user_session = request1.getSession().getAttribute("USER_SESSION");
if (request1.getSession().getAttribute("USER_SESSION")==null){
response1.sendRedirect("/Error.jsp");
}
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
边栏推荐
猜你喜欢

Mlx90640 infrared thermal imager temperature measurement module development notes (I)

Mlx90640 infrared thermal imager temperature measurement module development notes (4)

Qt 6.2的下载和安装

看一个双非二本(0实习)大三学生如何拿到阿里、腾讯的offer

Advanced introduction to digital IC Design SOC

【成长必备】我为什么推荐你写博客?愿你多年以后成为你想成为的样子。
![[deployment of deep learning model] deploy the deep learning model using tensorflow serving + tornado](/img/62/78abf16bb6c66726c6e394c9fb4f81.png)
[deployment of deep learning model] deploy the deep learning model using tensorflow serving + tornado

Swift creates weather app

MLX90640 红外热成像仪测温模块开发笔记(五)

数据库MySQL详解
随机推荐
Common methods of JS digital thousand bit segmentation
salt常见问题
Introduction to Verdi Foundation
NLM5系列无线振弦传感采集仪的工作模式及休眠模式下状态
Qt 6.2的下载和安装
[RNN] analyze the RNN from rnn- (simple|lstm) to sequence generation, and then to seq2seq framework (encoder decoder, or seq2seq)
[deployment of deep learning model] deploy the deep learning model using tensorflow serving + tornado
rospy Odometry天坑小计
记录一些JS工具函数
framework打包合并脚本
Introduction to arm GIC
ISP image signal processing
SystemVerilog语法
Swift creates weather app
I2C也可总线取电!
一.初始MySQL,MySQL安装、配置环境、初始化
Solve the Chinese garbled code error of qtcreator compiling with vs
Mlx90640 infrared thermal imaging sensor temperature measurement module development notes (II)
看一个双非二本(0实习)大三学生如何拿到阿里、腾讯的offer
Arm preliminaries