如何在春季发送发送状态代码作为404响应而不是404.jsp作为html响应? [英] How to send the send status code as response for 404 instead of 404.jsp as a html reponse in spring?

查看:74
本文介绍了如何在春季发送发送状态代码作为404响应而不是404.jsp作为html响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在春季创建了Web应用程序并处理了404和500的异常映射.如果系统找不到用于请求的URL的任何资源,它将重定向到自定义404.jsp而不是常规的404页面.一切正常,直到决定添加我的应用程序中有一个Web服务.我还包含一个控制器作为Web服务,该控制器没有视图,需要通过curl命令调用.

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.

用户可能会考虑更改curl脚本.如果他们更改了URL,它应该显示404状态代码,但是它将返回自定义的404.jsp作为html响应而不是状态代码.因为分派器servlet将使用/来获取所有url. *.

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?

请分享您的建议.

推荐答案

Spring 3.2引入了

Spring 3.2 introduced the @ControllerAdvice, and as mentioned in the documentation:

通常用于定义 @ ExceptionHandler

这意味着您可以使用@ControllerAdvice来辅助@Controller,如下所示:

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.

这篇关于如何在春季发送发送状态代码作为404响应而不是404.jsp作为html响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆