It contains a login method that will try to look-up a user based on a userName and userPassword combination entered on the login page. When the user is found it is assigned to the currentUser variable and a redirect to the home page is returned.
If the user is not found, a redirect to the login page is returned. A logout method will invalidate the session and the redirect to the logout page will make sure that the previous data is longer available.
The isLoggedIn method will be used by the LoginFilter to check if a user is logged in. It checks the value of the currentUser which is only set after a successful login. The isLoggedInForwardHome method will return a redirect to the home page in case a user is already logged in. Do not provide a setter for the currentUser variable, as this potentially allows a way to circumvent the login method!
Both fields apply some basic validation in that they are both required and need a minimum length of 3 characters. The 'Login' button will pass the entered values and call the login method on the UserManger bean. At the bottom of the page, a number of links are included that make navigating the example easier.
The first panel is shown in case a user is not logged in and contains a confirmation of the fact that the user is logged out. The second panel is shown in case the user is still logged in and provides a 'Logout' button together with a reminder that the user is still logged in. The page contains a basic welcome message returning the full name of the user using the getName method. In addition, a Logout button is available which allows a user to invalidate the session. It contains links to make navigating the example easier.
Security The LoginFilter class is a Servlet Filter that will be used to restrict access to the home page. When called, it will try to retrieve the UserManager from the ServletRequest. If the isLoggedIn returns true then the call is allowed through. In all other cases, a redirect is done to the login page.
Note that the session attribute name used to retrieve the UserManager is the name of the managed bean. The class is annotated with Configuration which indicates that the class can be used by the Spring IoC container as a source of bean definitions.
A FilterRegistrationBean is created which registers filters in a Servlet 3. Open a web browser and enter the following URL: The result should be that below page is displayed: Click the Logout button and a redirect to the logout page should happen as shown below. If you would like to run the above code sample you can get the full source code here. If you found this post helpful or have any questions or remarks, please leave a comment below.