Home > Back-end >  Spring Boot: managing APIs over multiple html pages
Spring Boot: managing APIs over multiple html pages

Time:04-23

i am building a web application using Spring Boot and HTML pages.

In multiple HTML pages I am using the same navbar:

<ul > 
            <li >
                <a href="/home" >Home</a>
            </li>
            <li >
                <a href="/user/showAllProducts" >All Products</a>
            </li>

Now I had to change the URL of the API that shows all products (/user/showAllProducts) and I had to change about 10 HTML pages.

Is there an easy way to manage all API URLs in one config file (application.properties?) and directly injecting them in HTML pages? The list item that will show all products is just one example of many other links in the navbar.

Thanks a lot for your help

CodePudding user response:

The best way to do this is in the context of a partial. If you would like to use something like thymeleaf or jsp you can insert your navbar as one line in each HTML or JSP file and then anytime you change the particular partial file (navbar, header, footer, etc) it will be inserted into whatever page is being displayed in the web app.

Here is a sample in documentation for Spring.

https://www.baeldung.com/spring-thymeleaf-fragments

CodePudding user response:

You can use ${@environment.getProperty('key')} to read property in the application.properties and use th:fragment to create a reusable fragment for your pages.

First, create a nav.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
  <ul th:fragment="nav" >
    <li >
      <a th:href="${@environment.getProperty('your.home.property.here')}" >Home</a>      
    </li>
    <li >
      <a th:href="${@environment.getProperty('your.products.property.here')}" >All Products</a>
    </li>
</body>
</html>

and use th:replace in your pages.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Hello Thymeleaf</title>
</head>
<body>
    <div th:replace="nav :: nav"></div>
</body>
</html>
  • Related