Menu

Get requested page URL from request in Spring Boot

How to get the requested URL information in a Spring security project so that we can redirect the user to the secure or right page after successful login. On every request Spring security stores the following information in the session key "SPRING_SECURITY_SAVED_REQUEST". This way will help us to get the last requested URL or request from where a user started the authentication request that redirected the user to the login page.

SPRING_SECURITY_SAVED_REQUEST key spring boot-request-url
SPRING_SECURITY_SAVED_REQUEST

Below is the code snippet to get the requested url from the "SPRING_SECURITY_SAVED_REQUEST" key.

DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession()
        .getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    	if(savedRequest != null) {
    		String previousPageUrl = savedRequest.getRedirectUrl();
    		
    	} 

This will helps us to redirect the users to the secure page after successful login. Thank you, hope this solves your problem.

How to get the last path segment of an URL using Java

With any programming language, we come at some point where we need the last segment of the URL to manage and moderate the request and response. Hence with this sample Java program, we will see how we can get the last segment of the URL or URI after a slash (/).

public class JavaSubStringSample {

	public static void main(String[] args) {
		String path = "http://localhost/customize";
		String finalName = path.substring(path. lastIndexOf('/'));
		System.out.println(finalName);
	}
}


The above program will return the last segment of a given URL from the path variable. i.e. /customize. You may also remove the special charecter slash by adding +1 after lastIndexOf method in substring method.


Java LastIndexOf() - rashid jorvee
Screenshot of result



Get page or file name from URL using JavaScript

Read the path of the current browsing page from DOM using the below JavaScript statement. Let's assume the URL of the page is "https://rashidjorvee.blogspot.com/2020/07/remote-debugger-in-eclipse.html"

var path =window.location.pathname;


After running the above statement value of path will return "/2020/07/remote-debugger-in-eclipse.html"

Now, split the path with slash(/) to get the last occurrence, which will be the final page name URL.

var page = path.split("/").pop();

After running the above statement the value of the page will be "remote-debugger-in-eclipse.html"

Now, if we want to remove the extension .html then run the below statement which will manipulate the value of the page variable.

var name = page.substr(0, page.lastIndexOf('.'));

After running the above statement the value gets assigned to the name variable "remote-debugger-in-eclipse"