You need to implement a filter that will take the login from the session, look at its presence and, if it does not exist, restrict access to certain pages. How can I do that?

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpSession session=((HttpServletRequest)request).getSession(); if(session.getAttribute("login")==null){ //??? } } 
  • if not found, redirect to the default page response.sendRedirect("/") (resp) - Tsyklop

1 answer 1

It is better to take from the session not a login, but an object of the class User (which has the id, login, password, ...) fields.

To do this, you need to implement a filter that will check whether the user has passed authentication (presence of an object in the session) and whether the user is on the login or registration page (otherwise the filter will always be redirected). If not, then redirect the user to the login.jsp page. Yes — run the next filter or servlet. And bind it (in the web.xml file) to the pages to which access is restricted:

 <filter> <filter-name>LoginFilter</filter-name> <url-pattern>здесь перечислить все страницы, к которым доступ ограничен</url-pattern> <filter> 

Filter itself:

 public class LoginFilter implements Filter { @Override public void init(FilterConfig config) {} @Override public void destroy() {} @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); String loginURL = request.getContextPath() + "/login"; String registrURL = request.getContextPath() + "/registr"; boolean loggedIn = session != null && session.getAttribute("user") != null; boolean loginRequest = request.getRequestURI().equals(loginURL) || request.getRequestURI().equals(loginURL + ".html"); boolean registrRequest = request.getRequestURI().equals(registrURL) || request.getRequestURI().equals(registrURL + ".html"); if(loggedIn || loginRequest || registrRequest) { chain.doFilter(req, res); } else { response.sendRedirect("login.html"); } } } 
  • accidentally there is no url pattern like "everything except .."? Suppose I have a lot of pages, and I want to give access only to "register" and "log in" or maybe another page - Vladislav Solopov
  • one
    @VladislavSolopov unfortunately does not exist. But you can do the following: the registration and authorization pages should be placed in the root folder, the pages for authorized users should be placed in the user folder and "matched" with their url-pattern /user/* , for the admin - /admin/* , etc. I think the idea you understand. - not a Programmer