Swagger UI is not loading after adding #PathVariable Resource to Controller - spring-boot

I have Spring Boot and Swagger Integration in my application. I have added one more resource in my existing controller after that, swagger ui stops loading
http://localhost:8080/swagger-ui.html page is not loading and giving HTTP ERROR 406 Error
One more thing if I remove #PathVariable from below API then swagger-ui is loading successfully.
Added below resource in existing controller
#ApiOperation(value = "Get Employee Information")
#GetMapping("/{employeeId}")
public EmployeeResponse employeeInfo(
#PathVariable("employeeId") String employeeId,
#RequestHeader(value = "x-client-id", required = false) String xclientId){
return service.getEmployeeInfo();
}
Below library versions I am using -
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.10.RELEASE'
compile 'io.springfox:springfox-swagger-ui:2.6.1'
compile 'io.springfox:springfox-swagger2:2.6.1'
When I try to load swagger-ui.html, getting
Client : [UnknownClient] - An exception was thrown by a controller Could not find
acceptable representation:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable
representation
I think newly added resource path is conflicting with swagger-ui.html root path. I cannot change the resource path and also swagger ui path as api contract is already decided .

Related

No webpage was found for the web address: http://localhost:8080/ in Spring generated by codegen with swagger

I am learning swagger using the example pet store in the swagger editor: https://editor.swagger.io/
The code for spring is generated and I does not change anything. However, everytime I run it on http://localhost:8080, it gives the error message
This localhost page can’t be found
No webpage was found for the web address: http://localhost:8080/
HTTP ERROR 404
But I believe I am supposed to see something like in the following website:
https://petstore.swagger.io/
May I ask how to solve this issue? Many thanks.
I follow the URL in the controller class HomeController.
#Controller
public class HomeController {
#RequestMapping(value = "/")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}
You might be visiting the wrong URL. Try out http://localhost:8080/<base-url>/swagger-ui.html
Additionally, you could refer this link for a basic setup.
It appears the context path is v2.
You should be able to access the demo at:
http://localhost:8080/v2/<endoint>
Try accessing:
http://localhost:8080/v2/swagger-ui.html
The context path is defined in a configuration file titled application.properties located under src/main/resource. The file contains the following:
springfox.documentation.swagger.v2.path=/api-docs
server.contextPath=/v2
server.port=8080
spring.jackson.date-format=io.swagger.RFC3339DateFormat
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
The context path is defined under server.contextPath.

Swagger not generating paths in yaml/json file when code is compiled

Trying to generate API documentation for a spring boot application using swagger. Using swagger-maven-plugin to generate yaml documentation from code. After compiling, the generated yaml/json file does not contain any path. However the controller class where the APIs are defined is getting scanned. But none of the APIs defined there are showing up in documentation. However accessing http://localhost:8080/api-docs shows a json and that is listing all the APIs as expected. What could be the issue? I have made sure of the following:
controller is annotated with #Api
tag value is set to false in pom.xml
basepath is the same across pom and controller class
All API paths are of the form http://localhost:8080/{id}/
Got my problem resolved. The Controller class methods were not declared public and hence was not showing up in swagger.yaml and json files even though the api-docs were listing them.
Try mapping your controller into a path.
Eg:- #Controller #RequestMapping(value = "/api")
For further clarification you can refer this article: https://www.baeldung.com/spring-controllers

Spring cloud Feign:no suitable HttpMessageConverter found for response type [class org.springframework.web.servlet.ModelAndView]

I have a service which has a url that return ModelAndView Object.
In its own point, I can access the website. But when I use spring cloud feign to invoke that url, it comes out that no suitable HttpMessageConverter found for response type [class org.springframework.web.servlet.ModelAndView] and contentType text/html. Here is my feign client.
Please try to change empList() method in your ConsumerController class like below.
public String empList() {
return empService.empList();
}
ModelAndView is not the actual response of /emplist from EmpController. It will be handled by DispatchServlet and ViewResolver will resolve the actual view with your view name - emp. So, from the view of ConsumerController, The response will be String object.
Anyway, I'm not sure that it's a good idea that accessing another web page via feign client in your case. Because if the original html page contains additional resources like images that existing in your origin server, it will not be served.

How to send the send status code as response for 404 instead of 404.jsp as a html reponse in spring?

I created web application in spring and handled exception mappings for 404 and 500.If system doesn't find any resources for requested URL it redirects into custom 404.jsp instead of regular 404 page.Everything works fine till have decided to add a webservice in my app.I have included one more controller as a webservice there is no view for this controller and this needs to be invoke through curl command.
User may get into change the curl script.If they changed the URL it should show 404 status code.But it returns the custom 404.jsp as a html response instead of status code.Because dispatcher servlet will takes all urls with /*.
How I can solve this issue?
Please share your suggestions.
Spring 3.2 introduced the #ControllerAdvice, and as mentioned in the documentation:
It is typically used to define #ExceptionHandler
That means you can use the #ControllerAdvice to assist your #Controller like the following:
#ControllerAdvice
class GlobalControllerExceptionHandler {
#ResponseStatus(HttpStatus.NOT_FOUND) // 404
#ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
For further details please refer to this tutorial and this answer.

How can I tell if Spring has loaded my #Controller?

Is there a way to tell if Spring has loaded my #Controller?
I'm requesting a URL but I'm not hitting my controller and I can't figure out why
I'm loading controllers by doing a component scan
<context:component-scan base-package="com.example.app.web"/>
Other controllers in the same package as my failing controller are working fine.
My controller code is:
#Controller
#RequestMapping(value = "/app/administration/ecosystem")
public class AppEcosystemController {
#Autowired
EcosystemManagerService ecosystemManagerService;
#RequestMapping(value = "/Foo", method = RequestMethod.GET)
public String getEcosystem() {
/* Implementation */
}
The first thing I'd like to do is to be sure that this controller is getting picked up by the component scan.
Any suggestions?
Just enable logging for your application, you can find this information at INFO level
For example in my application I have a controller named UserController.
The following log4j.properties does the trick.
log4j.rootLogger=INFO, FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=../logs/rest-json.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
I can see in the log that RequestMappingHandlerMapping mapped my controller (scroll all the way to the right).
07:28:36,255 INFO RequestMappingHandlerMapping:182 - Mapped "{[/rest/**/users/{id}],methods=[GET],params=[],headers=[],consumes=[],produces=[text/xml || application/json],custom=[]}" onto public org..domain.User org.ramanh.controller.UserController.getUser(java.lang.String)
07:28:36,255 INFO RequestMappingHandlerMapping:182 - Mapped "{[/rest/**/users],methods=[POST],params=[],headers=[],consumes=[],produces=[text/xml || application/json],custom=[]}" onto public void org..controller.UserController.addUser(org...domain.User)
If you are still unsure I would suggest adding a method annotated with #PostConstruct.
You could easily look up the message in the log or place a break point in this method.
#PostConstruct
protected void iamAlive(){
log.info(“Hello AppEcosystemController”)
}
If you find that your controller is initialized correctly but still the url is not accessible.I would test the following
You are getting 404 error - maybe you are not pointing to the correct
url (do not forget to add the application as prefix to the url)
You are getting 404 error - Dispatcher servlet mapping in web.xml doesn't meet
the url above
You are getting 403/401 – maybe you are using
spring security and it’s blocking the url
You are getting 406 – your
content type definition is conflicting with your request
You are getting 50x – something is buggy in your code
I made an ApplicationContextDumper. Add it into application context, it will dump all beans and their dependencies in the current context and parent contexts (if any) into log file when the application context initialization finishes. It also lists the beans which aren’t referenced.
It was inspired by this answer.
You could start out with enabling debug logging for Spring as outlined here.
I'd also recommend leveraging the MVC testing support, which you'll find in the spring-test jar. Details on how to use it can be found here and here.

Resources