lapots
lapots

Reputation: 13395

@Controller and @RequestMapping in custom error controller

I have application that uses swagger and websocket beside regular REST. Swagger has default endpoint /api/swagger-ui.html and websocket has default endpoint /api/websocket.

I wanted to implement the custom controller that would redirect internal errors to a page. Originally I did it like this

@Controller("/error")
public class ErrorPageController implements ErrorController {
    ....    
    @GetMapping
    public String handleGetError(HttpServletRequest request) {
        return handleError(request);
    }
    ....

However it led to redirects when I used swagger and websocket endpoints. When I changed it

@Controller
@RequestMapping("/error")
public class ErrorPageController

It started to work fine. Why is that?

Upvotes: 1

Views: 620

Answers (3)

Sumit Dhaniya
Sumit Dhaniya

Reputation: 596

Well Controller is a specialized component in spring and the value you are passing is treated as component name rather than path this controller needs to handle.

Upvotes: 1

Ori Marko
Ori Marko

Reputation: 58772

You should add @RequestMapping for defining the Path

 @RequestMapping("error")

Upvotes: 0

Anish B.
Anish B.

Reputation: 16469

I think the problem is with @Controller("/error")

According to Spring Docs:

@Controller

The annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

The optional element that you can pass :

@Controller(String value)

The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an auto-detected component.

It can be concluded that /error in @Controller("/error") is just a component name rather than a path.

Upvotes: 1

Related Questions