当前位置:网站首页>Servlet filter details
Servlet filter details
2022-07-26 05:53:00 【A rookie is a great God】
Writing a springmvc The project wants to intercept user requests , Only logged in users can access resources . At this time, you can use SpringMVC Interceptor Intercepter, But this can only be limited to SpringMVC Use in , If you want to be more general , Best use Servlet Filter To achieve this requirement .
This article will show you through several practical examples Servlet Medium Filter Use .
Why do we need to use Filter?
Usually we use session To save the login user's information , By getting from session Take out the saved attribute value to judge whether the user logs in , But if we have a large number of request methods , If everyone judges in this way, there will be a lot of duplicate code , In the future, we want to change the logic , That has to change all the request methods , So this is not desirable .
This is the time to use Servlet Filter It's time , It's pluggable , For ordinary action The method is transparent . It will execute other logic before executing other methods or returning the results to the client .
We will use in the following scenarios Servlet Filter:
- Write the requested parameters to the log file
- Unified authorization and verification of resource access
- When the request reaches the actual Servlet Format the request content or request header before
- Compress the returned data and send it to the client
- Modify the returned content , Add some cookie、header Etc
As mentioned earlier ,Servlet It's pluggable , It can be done by web.xml Whether to use . If we define multiple Filter, A filter chain will be formed . By implementing the interface javax.servlet.Filter To create a filter .
Filter Interface
Filter The interface contains three methods related to the life cycle , And by the Servlet Container to manage . They are :
1 | void init(FilterConfig paramFilterConfig) |
When the container initializes this Filter Is called when , And will only be called once . So in this method, we can initialize some resources . FilterConfig Will be used by containers for Filter Provide initialization parameters and Servlet Context object . We can throw... In this method ServletException abnormal .
1 | doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain) |
This method is called every time the filter is performed ,request and response Is passed in as a parameter ,FilterChain Represents the filter chain , This is a typical example of the implementation of the responsibility chain pattern .
1 | void destroy() |
This method is unloaded from the container filter Is called when . So we can put filter Some resources used are released .
WebFilter annotation
stay Servlet3.0 Notes are introduced in javax.servlet.annotation.WebFilter. No need to configure , Simple and practical , But if you need to change it often Filter Logically , I still suggest you in web.xml Configuration in file , Because the code must be rewritten after modification to take effect .
web.xml Medium Filter Configuration details
Make a statement like this filter:
1 2 3 4 5 6 7 8 | <filter> <filter-name>RequestLoggingFilter</filter-name> <!-- mandatory --> <filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class> <!-- mandatory --> <init-param> <!-- optional --> <param-name>test</param-name> <param-value>testValue</param-value> </init-param> </filter> |
Then define a mapping:
1 2 3 4 5 6 | <filter-mapping> <filter-name>RequestLoggingFilter</filter-name> <!-- Required --> <url-pattern>/*</url-pattern> <!-- url-pattern or servlet-name At least one must be specified --> <servlet-name>LoginServlet</servlet-name> <dispatcher>REQUEST</dispatcher> </filter-mapping> |
Log and login verification filter Example
Here is login.html page :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!DOCTYPE html> <html> <head> <meta charset="US-ASCII"> <title>Login Page</title> </head> <body> <form action="LoginServlet" method="post"> Username: <input type="text" name="user"> <br> Password: <input type="password" name="pwd"> <br> <input type="submit" value="Login"> </form> </body> </html> |
LoginServlet Be responsible for verifying whether the client has logged in :
LoginServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "password";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins
session.setMaxInactiveInterval(30*60);
Cookie userName = new Cookie("user", user);
userName.setMaxAge(30*60);
response.addCookie(userName);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
|
After passing the verification, jump to LoginSuccess.jsp:
LoginSuccess.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
String user = (String) session.getAttribute("user");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
}
}
%>
<h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
<br>
User=<%=user %>
<br>
<a href="CheckoutPage.jsp">Checkout Page</a>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
|
We don't need to verify when exiting , Exit page is :
CheckoutPage.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<h3>Hi <%=userName %>, do the checkout.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
|
LogoutServlet Execute when the user clicks the exit button :
LogoutServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.journaldev.servlet.session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session != null){
session.invalidate();
}
response.sendRedirect("login.html");
}
}
|
Now let's create the log and login authentication filter:
RequestLoggingFilter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package com.journaldev.servlet.filters;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
/**
* Servlet Filter implementation class RequestLoggingFilter
*/
@WebFilter("/RequestLoggingFilter")
public class RequestLoggingFilter implements Filter {
private ServletContext context;
public void init(FilterConfig fConfig) throws ServletException {
this.context = fConfig.getServletContext();
this.context.log("RequestLoggingFilter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
Enumeration<String> params = req.getParameterNames();
while(params.hasMoreElements()){
String name = params.nextElement();
String value = request.getParameter(name);
this.context.log(req.getRemoteAddr() + "::Request Params::{"+name+"="+value+"}");
}
Cookie[] cookies = req.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
this.context.log(req.getRemoteAddr() + "::Cookie::{"+cookie.getName()+","+cookie.getValue()+"}");
}
}
// pass the request along the filter chain
chain.doFilter(request, response);
}
public void destroy() {
//we can close resources here
}
}
|
And then there's another one Filter:
AuthenticationFilter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package com.journaldev.servlet.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {
private ServletContext context;
public void init(FilterConfig fConfig) throws ServletException {
this.context = fConfig.getServletContext();
this.context.log("AuthenticationFilter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
this.context.log("Requested Resource::"+uri);
HttpSession session = req.getSession(false);
if(session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))){
this.context.log("Unauthorized access request");
res.sendRedirect("login.html");
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
public void destroy() {
//close any resources here
}
}
|
Note that we are not static for any html The page or LoginServlet To verify , And now we have web.xml Configuration in file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>ServletFilterExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>RequestLoggingFilter</filter-name>
<filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class>
</filter>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.journaldev.servlet.filters.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestLoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
|
Next, let's test the effect .
边栏推荐
- 2022 National latest fire-fighting facility operator (Senior fire-fighting facility operator) simulation test questions and answers
- 高效,可靠,安全的串口通讯开源方案
- Etcd database source code analysis - cluster membership changes log
- 日志收集分析平台搭建-1-环境准备
- Ros2 knowledge: DDS basic knowledge
- Jdbc流式查询与游标查询
- 金仓数据库 KingbaseES SQL 语言参考手册 (10. 查询和子查询)
- [cloud native] record of feign custom configuration of microservices
- 光量子里程碑:6分钟内解决3854个变量问题
- flex布局
猜你喜欢

中文文本纠错任务简介

1.12 basis of Web Development

CANoe-XML在Test Modules中的应用

Kingbasees SQL language reference manual of Jincang database (10. Query and sub query)

语法泛化三种可行方案介绍
![[MySQL must know and know] time function number function string function condition judgment](/img/b2/aa15bf4cd78a3742704f6bd5ecb9c6.png)
[MySQL must know and know] time function number function string function condition judgment

Redis事务

Mba-day28 concept of number - exercise questions

Kingbasees SQL language reference manual of Jincang database (6. Expression)

Unity2D 动画器无法 创建过渡
随机推荐
Establishment of log collection and analysis platform-1-environment preparation
二叉树的性质 ~
Mba-day29 arithmetic - preliminary understanding of absolute value
Ros2 knowledge: DDS basic knowledge
Flex layout
MBA-day29 算术-绝对值初步认识
How to view the container name in pod
Embedded general learning route arrangement
Kingbasees SQL language reference manual of Jincang database (9. Common DDL clauses)
K. Link with Bracket Sequence I dp
Project topic selection reference
Modifiers should be declared in the correct order 修饰符应按正确的顺序声明
Select sort / insert sort / bubble sort
Solution to slow download speed of vagrant
ES Cluster in Red status: what about write & delete operations?
中文文本纠错任务简介
Jincang database kingbasees SQL language reference manual (5. Operators)
柠檬班自动化学习毕竟
Blurring of unity pixel painting
How to name the project version number? Looks like cow b