Home > Back-end >  Spring boot thymeleaf <href> URL wrong
Spring boot thymeleaf <href> URL wrong

Time:03-24

Why my href URL will autofill the word ?

     //commodityDetail.html
     <li><a href="/">Home</a></li>
     <li><a href="commodity">Products</a></li>

First URL : http://localhost8080 this is correct

Second URL : http://localhost:8080/commodityDetail/commodity this is wrong

The correct should be http://localhost:8080/commodity

I do not know why does it become " /commodityDetail/commodity "

//Controller
@GetMapping("/commodityDetail/{id}")
    public String commodityDetail(@PathVariable Long id,HttpSession session, Model model) {
        CommodityBean commodityBean = commodityService.findCommodityById(id);
        model.addAttribute("commodity", commodityBean);
        model.addAttribute("isLogin", memberService.isLogin(session));

        return "commodityDetail";

The correct should be http://localhost:8080/commodity

CodePudding user response:

If you want a server relative url, you should use the syntax:

<li><a th:href="@{~/commodity">Products</a></li>

However, since you are not even using th:href in this case, the reason that <a href="commodity">Products</a> is linking to /commodityDetail/commodity is because href="commodity" is a relative url. A relative url searches in the subdirectory of the current page.

So if you are currently viewing http://localhost:8080/commodityDetail/, any relative urls will be appended to http://localhost:8080/commodityDetail/.

CodePudding user response:

Thymeleaf provides multiple formats — including context-relative URLs which are relative to the current root directory.

So if your application is configured to use the commodityDetail context path, then the commodityDetail will be the context name utilized in your URLs. Which is why you are are seeing it "auto fill".

For example, if you have the following url:

<a th:href="@{/commodity/}">Products</a>

Then it will render as the following:

<a href="/commodityDetail/commodity/">Products</a>
  • Related