We may often use this function, for example, sometimes, we do not want users to log in to access the backend operation page, and such illegal access will make the system extremely unsafe, so we often need to log in before authorizing access to other pages, otherwise only the login page will appear. Of course, my idea:
One is to make a session judgment on the jsp page. If the user's session does not exist, it will jump to the login page. Otherwise, execute the jsp page code, but you will find that the logic is simple, but it is very troublesome. If there are many jsp pages, then you have to write multiple judgments.
Another way is to use filters to perform filter verification when accessing the page. If the user session exists, access the page. Otherwise, you will jump to the login page to log in, save the session and access other pages.
Here is my implementation
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class LoginFilter implements Filter { public static final String login_page = "/test/admin/"; public static final String logout_page = "/test/admin/Public/"; public void destroy(){ } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; String currentURL = (); String ctxPath = (); // When removing the project name, access the current path of the page String targetURL = (()); HttpSession session = (false); //Judge the current page, if the current page is not a login page if(!("/admin/Public/".equals(targetURL))){ ("1"+targetURL+"ctxPath:"+ctxPath+"currentURL:"+currentURL); // Make a judgment when it is not a login page. If it is not a login page and there is no session, then jump to the login page. if(session == null || ("admin") == null){ (logout_page); return; }else{ //This means it is correct, and you will look for the next link. If it does not exist, you will perform normal page jumps. (request, response); return; } }else{ //This means that if the current page is a login page, jump to the login page (request, response); return; } } public void init(FilterConfig filterConfig)throws ServletException{ } }
Next, configure it in
<filter> <filter-name>LoginFilter</filter-name> <filter-class></filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> //This means that it is valid for all files with jsp suffix, and others are invalid <url-pattern>*.jsp</url-pattern> </filter-mapping>
Then, this function is implemented.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.