How to Add a Public Landing Page
If an application to have a landing page that is accessible to everyone at first, the user can then signup or login to access specific features. For achieve this we can add a public view page and set up the security constraints to allow access to the view page.
In this example, we have a view page that anyone can access. Then they can click the link to access the secure pages.
This project has the following mods
1. Updated security configs to allow public access to landing page
2. Updated controller to send requests to landing page
3. New landing page
Details below
---
1. Updated security configs to allow public access to landing page
See the config below. It will "permit all" access to the landing page "/". Also, for successful logout it will redirect to the landing page "/"
File: DemoSecurityConfig.java
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .antMatchers("/").permitAll() // allow public access to home page
- .antMatchers("/employees").hasRole("EMPLOYEE")
- .antMatchers("/leaders/**").hasRole("MANAGER")
- .antMatchers("/systems/**").hasRole("ADMIN")
- .and()
- .formLogin()
- .loginPage("/showMyLoginPage")
- .loginProcessingUrl("/authenticateTheUser")
- .permitAll()
- .and()
- .logout()
- .logoutSuccessUrl("/") // after logout then redirect to landing page (root)
- .permitAll();
- }
2. Updated controller to send requests to landing page
In the controller file, added new "/" mapping to send to landing page. And changed the original home mapping to "/employees". see changes in bold.
File: DemoController.java
- @GetMapping("/")
- public String showLanding() {
- return "landing";
- }
- @GetMapping("/employees")
- public String showHome() {
- return "home";
- }
3. New landing page
Created a new view page for landing information. Anyone can access this page
File: src/main/webapp/WEB-INF/view/landing.jsp
- <html>
- <head>
- <title>luv2code Landing Page</title>
- </head>
- <body>
- <h2>luv2code Landing Page</h2>
- <hr>
- <p>
- Welcome to the landing page! This page is open to the public ... no login required :-)
- </p>
- <hr>
- <p>
- <a href="${pageContext.request.contextPath}/employees">Access Secure Site (requires login)</a>
- </p>
- </body>
- </html>
To test the application, be sure to open a new private/incognito window.
Now when you run the application, anyone can access the public home page without logging in. If they follow through on the link, then they will be required to login.
Comments
Post a Comment