How do I get a Spring 3.0 controller to trigger a 404?
I have a controller with @RequestMapping(value = "/**", method = RequestMethod.GET)
and for some URLs accessing the controller, I want the container to come up with a 404.
The 404 error code is configured properly, but it will caused the “. htm” extension handling conflict between the “servlet container” and Spring's “DispatcherServlet“. To solve it, try change the 404. htm to other file extension, for example 404.
We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web. xml.
Just throw HttpException: throw new HttpException(404, "Page you requested is not found"); ASP.NET run-time will catch the exception and will redirect to the custom 404.
Now if you ask whether you can or cannot use threads within your controller request, yes you can but the way Spring handles requests, already handles that need of dispatching a new thread when its needed or re-use an existing pool Are Spring Boot and Spring Framework the same?
I would like to mention that there's exception (not only) for 404 by default provided by Spring. See Spring documentation for details. So if you do not need your own exception you can simply do this:
In order to be able to work with Spring MVC, let's deal with the Maven dependencies first: To get the latest version of the library, have a look at spring-webmvc on Maven Central. 4. Project Web Config Now, before looking at the controllers themselves, we first need to set up a simple web project and do a quick Servlet configuration.
Since these applications do not do any view rendering, there are no View Resolvers – the Controller is generally expected to send data directly via the HTTP response. Let's start with the MVC0-style controllers. 3. Maven Dependencies In order to be able to work with Spring MVC, let's deal with the Maven dependencies first:
Since Spring 3.0 you also can throw an Exception declared with @ResponseStatus
annotation:
@ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { ... } @Controller public class SomeController { @RequestMapping..... public void handleCall() { if (isFound()) { // whatever } else { throw new ResourceNotFoundException(); } } }
Starting from Spring 5.0, you don't necessarily need to create additional exceptions:
throw new ResponseStatusException(NOT_FOUND, "Unable to find resource");
Also, you can cover multiple scenarios with one, built-in exception and you have more control.
See more:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With