本文介绍了如何从 Grails 控制器返回 404/50x 状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,需要在某些条件下返回 404 页面和状态代码.我似乎无法找到如何在 Grails 中执行此操作.一位同事推荐了这种方法:

I have a controller that needs to return a 404 page and status code on certain conditions. I can't seem to find out how to do this in Grails. A coworker recommended this method:

response.sendError(HttpServletResponse.SC_NOT_FOUND)

它工作得很好,但不是很像 Grails.我知道 Rails 的 render 方法需要一个 status 参数,但 Grails 的 render 没有这样的功能.有什么我遗漏的吗?实现此目的的最佳方法是什么?

which works perfectly fine, but it's not very Grails-like. I know Rails' render method take a status argument, but Grails' render has no such functionality. Is there something I'm missing, what's the best way to accomplish this?

推荐答案

用自己的语句设置响应状态就足够了.它看起来并不太难看,而且非常简单:

Setting the response status with its own statement is good enough. It doesn't look too ugly and is pretty straightforward:

response.status = 404;

我自己和 也见过其他人这样做.由于它只是一个setter,你也可以在设置状态后做其他的事情.您最后设置的状态将是 HttpServletResponse 在实际将响应发送回客户端时使用的状态.

I've used this successfully myself and have seen others do it this way too. Since it's just a setter, you can also do other stuff after setting the status. Whichever status you set last will be what the HttpServletResponse uses when it actually sends the response back to the client.

这篇关于如何从 Grails 控制器返回 404/50x 状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 00:38