SpringMVC based Rest Service - StackOverflowError when path is not defined - java

I'm creating a project using the #RestController annotation of Spring 4. Everything is working fine, when I call a URL path that is configured I receive a well formatted answer or an error if something happened.
But, if I call a service in a path that is not defined, I'm getting the following exception:
java.lang.StackOverflowError
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:592)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:592)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:592)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
I know this error is happening because my request could not be mapped to a resource, but I'm wondering why I am not getting a 404 - Not found error type?
My DispatcherServlet is configured like this:
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
This is a sample of my Service classes:
#RestController
#RequestMapping("/Genotypes")
public class GenotypeService {
... #Autowired objects here ...
#RequestMapping(method=RequestMethod.GET)
public #ResponseBody List<Genotype> findGenotypesLike(#RequestParam(value="genName", required=false) String name, #RequestParam(value="like", defaultValue="false") Boolean like){
if(name == null){
return genotypeBO.findAllGenotypes();
}
return genotypeBO.findByName(name, like);
}
If I call http://localhost:8080/MyApp/Genotypes I get my response but if I call http://localhost:8080/MyApp/SomethingNotMapped the exception is thrown and the error code at the browser side is a 500 - Internal Server Error
By the way, my application is running on Apache Tomcat v7.0.
Thanks in advance for any suggestion.

Related

Getting 500 undocumented error as "Connection prematurely closed DURING response" after executing rest api for file upload

Created a rest api in Springboot application which takes file through POST rest api and do some processing and returns some response.
but when executed that post api it shows an error below as..
Connection prematurely closed during response
Code snippet for the restcontroller is as follows.
#CrossOrigin(origins="*")
#RestController
#RequestMapping("/")
public class Script{
#Autowired
ScriptService sevice;
private static final Logger logger = (Logger) LoggerFactory.getLogger(LensMigration.class);
#PostMapping("/api/v1/execute/script")
public ResponseEntity<Map<String, Integer>> executeScript(#RequestParam(value = "file") MultipartFile file)
throws IOException {
logger.info("inside endpoint!!!");
if (file.isEmpty()) {
throw new FileNotFoundException("file doen not exists!!");
} else {
BufferedReader csvReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
return new ResponseEntity<>(service.migrateOldRecords(csvReader), HttpStatus.OK);
}
}
}
I have used some loggers at start of controller to check if it is executing, but didn't get any logs printed.
May be error due to response time
so I have tried to increase the response time using servlet property but it didn't worked
server.connection-timeout=60000
could anyone help me here please.
Actually it is very strange to me that it gets solved by just adding the #RequestMapping annotation to different path.
The root cause of the issue was the endpoint inside controller was not visible. The actual error I was expecting is that 404 not found for this particular POST api.
I did get 404 not found error for another GET endpoint which I just written below this POST api.
So due to this 404 I was looking for visibility of the endpoint
and its gets resolved.

404 error when using spring to display jsp

the url that is being clicked in the home is
Edit
the method its accessing in the controller is
#GetMapping("/edit")
public ModelAndView editBrewery(#RequestParam("id") int id) {
return new ModelAndView("/editBrewery", "brewery", service.getBrewereriesID(id));
}
its not getting into the return in the #GetMapping method in the controller, i put a break point at the return and it goes into the 404 before it gets to the breakpoint
the utput that the tomcat console is giving is
WARNING: No mapping found for HTTP request with URI [/Assignment2/breweries/edit] in DispatcherServlet with name 'dispatcher'
Try just using Edit (without the previous url parts).

RESTful error response Spring instead of tomcat page

I want to return a custom JSON as response body in case of errors. I tried doing this for 404 error code. I created a controller which looks like this.
#RequestMapping("/**")
#Controller
public class IOTExceptionController {
public void handleInvalidURL() throws ResourceNotFoundException {
throw new ResourceNotFoundException("Requested resource does not exist."
+ " Please check the URL.");
}
}
And the ControllerAdvice class I've setup will return the response as JSON.
So whatever URL which will not be found in other controllers will be handled here and 404 error is returned.
Unfortunately, the Tomcat error page for 404 is all I'm getting. Can anyone please let me know whether there is any flaw in this logic/code?

spring RESTful service work fine, but throws an exception

I am creating a spring RESTful service, and it is working. My client send an object into a put request and my service receive this object perfectly, but after this, my client receive this exception: "org.springframework.web.client.HttpClientErrorException: 404 Not Found"
This is my client code:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = new Greeting(21l, FileUtils.toByteArray("src/main/resources/test.png"));
String url = "http://localhost:8080/DolphinRestServer/bulletin/put";
restTemplate.put(url,greeting);
And this is my server code:
#Service
#RequestMapping("/bulletin")
public class BulletinService {
#RequestMapping(method = RequestMethod.PUT, value = "/put")
public void put(#RequestBody Greeting greeting){
System.out.println("it's work fine and my greeting is here --------->"+greeting);
}
}
When tested, i get those messages:
-server side:
-Client side:
Your put method has a void return type. Additionally, it does not take the HttpServletResponse as a parameter. According to the Spring MVC documentation, when such a situation arises, Spring MVC uses the URL as the view name and attempts to render it. In your case, Spring MVC is attempting to find and load a view called /bulletin/put, which it can't find and hence the 404 message.
As you can see it is making another request at 20:40:34:085 DolphinRestServer/bulletin/bulletin/put in the server side giving an error page not found.
And it is because you are calling BulletinService twice.
You defined as a bean and it has an annotation. Make sure you are only loading/scanning this package once..
Remove #service annotation on BulletinService

Tomcat 7 default bad request page conflict #ControllerAdvice

I am currently developing a webservice which will always return json as a response to any request(all good request are working already). I would like to return a json when the http status of the request is a bad request(status 400 to be exact). I used the #ControllerAdvice of spring mvc to do the job:
#ControllerAdvice
public class RestErrorHandler {
#ExceptionHandler(Exception.class)
#ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Something went wrong. Please check your JSON REQUEST!")
public #ResponseBody ErrorClass processValidationError() {
// some stuff in setting the error response
return new ErrorClass();
}
But what happen is that it returns the default Tomcat 7 error message for bad request and not the json I set. processValidationError() will return an ErrorClass instance which will automatically be in json format using jackson plugin. Did I missed something?

Categories