Spring Boot — сопоставление запросов не будет принимать завершающую косую черту или несколько каталогов

Когда RequestMapping в моем контроллере, я могу сопоставить html-файл с «/», а другой с «/users». Однако попытка сопоставить «/users/» или «/users/test» не сработает. В консоли будет сказано, что конечная точка была сопоставлена, но при попытке доступа к ней я получу страницу с ошибкой 404.

package com.bridge.Bitter.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BitterController {

    //works
    @RequestMapping(value="/")
    public String getMainPage(){
        return "main.html";
    }

    //works
    @RequestMapping(value="/users")
    public String getUsersPage(){
        return "users.html";
    }

    //doesn't work, Whitelabel error page
    @RequestMapping(value="/users/")
    public String getUsersSlashPage(){
        return "users.html";
    }
    //doesn't work, Whitelabel error page
    @RequestMapping(value="/users/test")
    public String getUsersTestPage(){
        return "users.html";
    }

}

Мои application.properties содержат только «spring.data.rest.basePath=/api».

Если я перейду с @Controller на @Rest Controller, произойдет следующее:

package com.bridge.Bitter.controllers;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class BitterController {

    //works
    @RequestMapping(value="/")
    public String getMainPage(){
        return "main.html";
    }

    //returns a webpage with the text "users.html" on it instead of serving the html
    @RequestMapping(value="/users")
    public String getUsersPage(){
        return "users.html";
    }

    //returns a webpage with the text "users.html" on it instead of serving the html
    @RequestMapping(value="/users/")
    public String getUsersSlashPage(){
        return "users.html";
    }
    //returns a webpage with the text "users.html" on it instead of serving the html
    @RequestMapping(value="/users/test")
    public String getUsersTestPage(){
        return "users.html";
    }

}

Изменение функций с возврата строк на возврат

new ModelAndView("user.html")

работает для /users, но затем будет ошибка 404 для /users/ и /users/test.


person Justin Auger    schedule 03.07.2018    source источник


Ответы (1)


Вы пытаетесь отобразить один и тот же путь дважды. /users обрабатывается так же, как /users/, поэтому Spring не может решить, какой метод контроллера должен обрабатывать запрос.

Вы можете просто попробовать это:

package com.bridge.Bitter.controllers;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BitterController {

    @RequestMapping("/")
    public String getMainPage(){
        return "main.html";
    }

    @RequestMapping("/users")
    public String getUsersPage(){
        return "users.html";
    }

    @RequestMapping("/users/test")
    public String getUsersTestPage(){
        return "users.html";
    }
}

С другой стороны, при использовании @RestController аннотация, вы всегда возвращаете текст ответа в формате JSON, поэтому вы всегда получаете один и тот же результат.

person carlosdgomez    schedule 03.07.2018
comment
Даже если я сопоставляю только один, поскольку мой контроллер содержит только сопоставление для /users/, он не будет сопоставляться с localhost:8080/users/. То же самое, если у меня ПРОСТО есть /users/test. Однако /users работает. Имена методов не должны были совпадать, это была ошибка с моей стороны в вопросе. - person Justin Auger; 04.07.2018