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"); } } }
response.sendRedirect("/")(resp) - Tsyklop