How can I return a 404/50x status code from a Grails Controller?

血红的双手。 提交于 2019-12-29 04:05:08

问题


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)

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?


回答1:


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

response.status = 404;

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.




回答2:


response.sendError(404) will work with Grails UrlMappings whereas response.status = 404 does not for some reason. This is useful if you want to render a custom 404 error page, as opposed to just sending 404 back to the browser.




回答3:


I don't know what version this started in, but in Grails 2.2.1 you can do:

render(status: 503, text: 'Failed to do stuff.')

http://grails.org/doc/2.2.1/ref/Controllers/render.html




回答4:


response.sendError and response.setStatus are the only two ways I know of. If you static import HttpServletResponse, then it's not that 'un-grails-like'.



来源:https://stackoverflow.com/questions/1429388/how-can-i-return-a-404-50x-status-code-from-a-grails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!