Search code examples
javaspringswagger-ui

Swagger API of spring boot RESTful web service is not working due to servlet filter


The servlet filter suppresses many swagger responses (including images and CSS) to create a swagger-ul GUI screen on the browser. Please bypass such acts by the following code snippet.

@Component
public class DomainAuthorizationFilter implements Filter {


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if(httpRequest.getRequestURI().trim().toLowerCase().matches(".*swagger-.*|.*api-docs.*"))
        {           request.getRequestDispatcher(httpRequest.getServletPath()).forward(request, response);
            return;
        }
        else {
              // Your login in the filter.
        }
        chain.doFilter(request, response);
    } 
}

Solution

  • We need to add the said filter and inside our spring-boot controller, we need to put like -

    @ApiOperation(value = "description of method.", response = Object.class)
    @ApiResponses(value = { @ApiResponse(code = 200, message = "record found."),
            @ApiResponse(code = 404, message = "record not found") })
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "header_1", value = "Provide header_1 in the header.", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "header_2", value = "Provide header_2 in the header.", required = true, dataType = "string", paramType = "header") })  
    @GetMapping(value = "/getRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseDTO<AccountDashboardDTO> getRecord()
    {
        // Your business logic.
        return response;
    }