当前位置:网站首页>Login authentication filter
Login authentication filter
2022-06-12 05:48:00 【Fairy-KunKun】
In a JavaWeb In the project , For some special resources , Login is required to use
【 Settlement 】、【 download 】、【 Comment on 】
For functions like these , You need to log in first , And then you can use it
First check whether you are logged in
If you are not logged in , These resources cannot be used
Force login
otherwise : have access to
Previous practice : Such as home.jsp resources , You need to verify whether you are logged in
A unified extraction jsp,checkLogin.jsp, You need to control whether users log in jsp Use in <include> Tags introduced

/page/mymood/delete.do
| Servlet resources checkLogin.jsp It's not common anymore .
/page/mymood/publish.do
wait , There are many resources in the system that need access control
.jsp
-----》 resources Unification Cannot distinguish between suffixes
.do
.css

(1) Design a configuration file , It is used to configure the resources that need login control
![]()
urls=/page/user/home.jsp,/page/mymood/delete.do,/page/mymood/update.do
(2) Read authority file
package com.njwbhz.mood.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Read login authentication file
*/
public class AuthorityUtil {
private static List < String > urls = new ArrayList < String > ( );
public static List < String > load ( ) {
BufferedReader reader = null;
reader = new BufferedReader (
new InputStreamReader (
AuthorityUtil
.class
.getClassLoader ( )
.getResourceAsStream ( "authority" )
)
);
try {
String lineData = reader.readLine ( );
String[] resources = lineData.split ( "=" )[ 1 ].split ( "," );
urls = Arrays.asList ( resources );
} catch ( IOException e ) {
e.printStackTrace ( );
} finally {
if ( null != reader ) {
try {
reader.close ( );
} catch ( IOException e ) {
e.printStackTrace ( );
}
}
}
return urls;
}
}
(3) Testing tools
package com.njwbhz.mood;
import com.njwbhz.mood.util.AuthorityUtil;
import org.junit.Test;
import java.util.List;
public class TestAuthority {
@Test
public void load ( ) {
List < String > urls =
AuthorityUtil.load ( );
urls.forEach ( System.out :: println );
}
}

(4) Define filters
package com.njwbhz.mood.filter;
import com.njwbhz.mood.entity.User;
import com.njwbhz.mood.util.AuthorityUtil;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* Login validation filter
*/
public class AuthorityFilter implements Filter {
private List < String > urls;
@Override
public void init ( FilterConfig filterConfig ) throws ServletException {
// Load the file
urls = AuthorityUtil.load ( );
}
@Override
public void doFilter ( ServletRequest servletRequest , ServletResponse servletResponse , FilterChain filterChain ) throws IOException, ServletException {
// Every request can be AuthorityFilter Intercept
// The request is within the scope of validation ?
// First get the current URL What is it? ?
HttpServletRequest request = ( HttpServletRequest ) servletRequest;
HttpServletResponse response = ( HttpServletResponse ) servletResponse;
// Such as the current URL:http://127.0.0.1:8080/mood/page/user/login.do?xxxx
String currentUri = request.getRequestURI ( );// /mood/page/user/login.do?xxxx
String contextPath = request.getContextPath ( );
String currentURL = currentUri.substring ( contextPath.length ( ) );// /page/user/login.do?xxxx
if ( currentURL.contains ( "?" ) ) {
currentURL = currentURL.substring ( 0 , currentURL.lastIndexOf ( "?" ) );
}
// If in , Judge session
if ( urls.contains ( currentURL ) ) {
User user = ( User ) request.getSession ( ).getAttribute ( "user" );
if ( null != user ) { // It's already logged in
// release
filterChain.doFilter ( request , response );
} else {
// The login page
String path = request.getContextPath ( );
String basePath = request.getScheme ( )
+ "://" + request.getServerName ( )
+ ":" + request.getServerPort ( )
+ path + "/";
String loginUrl = basePath + "page/user/login.jsp";
response.setContentType ( "text/html;charset=UTF-8" );
PrintWriter writer = response.getWriter ( );
writer.write ( "<script type=\"text/javascript\">" );
writer.write ( "alert(\" Not signed in yet , Please log in first !\");" );
writer.write ( "window.top.location.href='" );
writer.write ( loginUrl );
writer.write ( "';" );
writer.write ( "</script>" );
writer.flush ( );
writer.close ( );
}
} else { // If not , Direct release
filterChain.doFilter ( request , response );
}
}
@Override
public void destroy ( ) {
}
}
(5) To configure
<filter >
<filter-name >authorityFilter</filter-name>
<filter-class >com.njwbhz.mood.filter.AuthorityFilter</filter-class>
</filter>
<filter-mapping >
<filter-name >authorityFilter</filter-name>
<url-pattern >/*</url-pattern>
</filter-mapping>
(6)home.jsp

(7) test
边栏推荐
猜你喜欢

IO to IO multiplexing from traditional network

Halcon 3D 深度图转换为3D图像

基于tensorflow的校园绿植识别

Role and understanding of proc/cmdline
![[long time series prediction] the [4] autocorrelation mechanism of aotoformer code explanation](/img/12/27531fc791b3f49306385831309c5e.png)
[long time series prediction] the [4] autocorrelation mechanism of aotoformer code explanation

Beginning is an excellent emlog theme v3.1, which supports emlog Pro

What is the lszrz protocol used at ordinary times? Talk about xmodem/ymodem/zmodem

Win10 desktop unlimited refresh

Leetcode simple problem: converting an integer to the sum of two zero free integers
![[grpc development] go language builds simple server and client](/img/24/06c3c1219ecad7e117f4df152e9ce7.jpg)
[grpc development] go language builds simple server and client
随机推荐
Lock and reentrankload
Halcon 用点来拟合平面
MySQL notes
[JS knowledge] easily understand JS anti shake and throttling
BlockingQueue interface introduction
Special materials | household appliances, white electricity, kitchen electricity
Tabulation skills and matrix processing skills
Word frequency statistics using Jieba database
Reverse linked list
Market trend report, technical innovation and market forecast of Chinese stump crusher
Leetcode simple problem: converting an integer to the sum of two zero free integers
Makefile文件编写快速掌握
Select gb28181, RTSP or RTMP for data push?
Detailed explanation of WiFi 802.1x authentication process
China Aquatic Fitness equipment market trend report, technical innovation and market forecast
Win10 desktop unlimited refresh
Why should state-owned enterprises go public
Chapter 7 - pointer learning
数据库实验三:数据查询
Go 面向接口编程实战