当前位置:网站首页>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
边栏推荐
- Mysql笔记
- Go interface implementation principle [advanced level]
- Reverse linked list
- Select gb28181, RTSP or RTMP for data push?
- Conversion of Halcon 3D depth map to 3D image
- 16. 最接近的三數之和
- 网络加速谁更猛?CDN领域再现新王者
- nrf52832--官方例程ble_app_uart添加led特性,实现电脑uart和手机app控制开发板led开和关
- [go] Viper reads the configuration file in the go project
- 利用jieba库进行词频统计
猜你喜欢

Redis memory obsolescence strategy

Legal liabilities to be borne by the person in charge of the branch

BlockingQueue interface introduction

FPGA语法的细节

个人申请OV类型SSL证书

Golang idea configures the agent to improve the speed of packages downloaded by go get

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

Redis cache data consistency and problems

How long is the company's registered capital subscribed

Review notes of naturallanguageprocessing based on deep learning
随机推荐
Flex/fixed upper, middle and lower (mobile end)
Redis cluster cluster capacity expansion and data migration
网络加速谁更猛?CDN领域再现新王者
Webrtc AEC process analysis
GRE protocol details
Database experiment I: data definition experiment guide
Understanding of distributed transactions
Towards End-to-End Lane Detection: an Instance SegmentationApproach
China's elastic belt market trend report, technical dynamic innovation and market forecast
json-c常用API
从传统网络IO 到 IO多路复用
Chapter 7 - pointer learning
Json-c common APIs
FPGA语法的细节
Redis memory obsolescence strategy
Mysql笔记
March 23, 2021
Golang idea configures the agent to improve the speed of packages downloaded by go get
Identification of campus green plants based on tensorflow
[grpc development] go language builds simple server and client