Search code examples
javaspring-mvcspring-bootthymeleafhttpsession

HttpSession to store URL


I'm wondering if it is bad practice to keep an "URL" attribute in the HttpSession to keep track of the previous page the user visited. I want to know the previous URL so I can conditionally perform different tasks depending on what the previous page was.

An example would be a controller class that changes the color of the web-page depending on how the user is accessing this page. If user pressed the button from "example.com/blue", it should redirect to the current page and make it blue. (if from "example.com/pink", it should make the page pink, etc.). This is done from

Url url = httpSession.getAttribute(url);
if (url.equals(blue)) {
    // make page blue
}
if (url.equals(pink)) {
    // make page pink
}

Hopefully this is making sense.

Thanks!


Solution

  • Yes, this is a bad practice. This will be hard to maintain. How would you even write a unit test?

    The tags in this question imply that you are using an MVC framework, but your solution looks like a misunderstanding of the MVC pattern.

    Urls belong to 'controller', page styling is 'view' and user's history is 'model'. If you need to store some information in HttpSession, make it protocol-independent. I would consider storing some kind of enum. Alternatively, the button can just pass the color as a request parameter.

    Also, there are users, who will open your page in two tabs.

    Try to implement your application in such a way that when you decide to reorganize the page structure, you don't have to reorganize the HttpSession as well.