如何让Spring 3.0控制器触发404?
我有一个控制器@RequestMapping(值= "/**",方法= RequestMethod.GET)和一些访问控制器的url,我希望容器提出一个404。
如何让Spring 3.0控制器触发404?
我有一个控制器@RequestMapping(值= "/**",方法= RequestMethod.GET)和一些访问控制器的url,我希望容器提出一个404。
当前回答
我想提一下,Spring默认提供了404异常(不仅是)。有关详细信息,请参阅Spring文档。所以如果你不需要自己的异常,你可以简单地这样做:
@RequestMapping(value = "/**", method = RequestMethod.GET)
public ModelAndView show() throws NoSuchRequestHandlingMethodException {
if(something == null)
throw new NoSuchRequestHandlingMethodException("show", YourClass.class);
...
}
其他回答
重写你的方法签名,使它接受HttpServletResponse作为参数,这样你就可以对它调用setStatus(int)。
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments
因为做同一件事至少有十种方法总是好的:
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class Something {
@RequestMapping("/path")
public ModelAndView somethingPath() {
return new ModelAndView("/", HttpStatus.NOT_FOUND);
}
}
你可以使用@ControllerAdvice来处理异常, 默认行为@ControllerAdvice注释类将帮助所有已知的控制器。
因此,当任何控制器抛出404错误时,它将被调用。
像下面这样:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
@ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
并将此404响应错误映射到web.xml中,如下所示:
<error-page>
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
希望能有所帮助。
从Spring 5.0开始,你不需要创建额外的异常:
throw new ResponseStatusException(NOT_FOUND, "Unable to find resource");
此外,你可以用一个内置异常覆盖多个场景,你有更多的控制。
看到更多:
ResponseStatusException (javadoc) https://www.baeldung.com/spring-response-status-exception
从Spring 3.0开始,你还可以抛出一个用@ResponseStatus注释声明的Exception:
@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();
}
}
}