Skip to content
Advertisement

How to make back button go to previous page dynamically based on previous page using Thymeleaf?

I have 3 html pages (Page A,B,C) where Page A and Page B will have a hyperlink that will direct to Page C. In Page C there will be a “Back” button.

So the question is, I want the “Back” button (Page C) go back to previous page based on the destination where user clicked the hyperlink from either (Page A) or (Page B). Is it possible to achieve this by using Thymeleaf other than using "javascript:history.go(-1)" on the “Back” button? So far I couldn’t find the solution all over the place.

Advertisement

Answer

You can use the referrer request header:

Do something like this:

public class MyController {

  @GetMapping
  public String myMethod(@RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer, Model model) {
    if( referrer != null ) {
      model.addAttribute("previousUrl", referrer);
    }
  }
}

Note that it might not always work. If a user directly enters the URL of page C in the browser, then there is no referrer URL.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement