英文:
How to bypass AEM default error handling?
问题
从在AEM运行的Sling servlet中直接返回自定义内容的HTTP错误响应是否可能?
背景
有一个Sling servlet,用于处理使用POST方法发送的表单。
@SlingServlet(
methods = HttpConstants.METHOD_POST,
resourceTypes = NameConstants.NT_PAGE,
selectors = SELECTOR)
public class MyServlet extends SlingAllMethodsServlet {
//...
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
//如果请求存在问题
Gson gson = new Gson();
gson.toJson(errorResponse, response.getWriter());
response.setContentType(MediaType.JSON_UTF_8.toString());
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
//...
}
//...
}
当它返回HTTP 400 Bad Request时,我想获取在Servlet中创建的JSON响应。然而,AEM返回一个HTML页面,由/apps/sling/servlet/errorhandler生成,只在内容开头添加了JSON。
{"errors":["The provided value is incorrect"]}
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>400 Bad Request</title></head>
<body>
<h1>400 Bad Request</h1>
<p>Cannot serve request to on this server.</p>
(...)
</body>
</html>
我知道可以创建自定义错误页面。问题是,我需要来自Servlet的验证错误以创建有意义的错误响应。
AEM版本:6.5
英文:
Is it possible to directly return a HTTP error response with custom contents from a Sling servlet running in AEM?
Background
There is a Sling servlet that processes forms sent with the POST method.
@SlingServlet(
methods = HttpConstants.METHOD_POST,
resourceTypes = NameConstants.NT_PAGE,
selectors = SELECTOR)
public class MyServlet extends SlingAllMethodsServlet {
//...
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
//if something is wrong with the request
Gson gson = new Gson();
gson.toJson(errorResponse, response.getWriter());
response.setContentType(MediaType.JSON_UTF_8.toString());
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
//...
}
//...
}
When it returns HTTP 400 Bad Request, I'd like to get the JSON response created in the servlet. Instead, AEM returns a HTML page, generated with /apps/sling/servlet/errorhandler, only with the JSON added at the beginning of the content.
{"errors":["The provided value is incorrect"]}
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>400 Bad Request</title></head>
<body>
<h1>400 Bad Request</h1>
<p>Cannot serve request to on this server.</p>
(...)
</body>
</html>
I am aware that it is possible to create custom error pages. The problem is that I need validation errors from the servlet to create a meaningful error response.
AEM version: 6.5
答案1
得分: 1
只需使用response.setStatus(...),而不是response.sendError(...)。
所以只需调用:
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
英文:
Just use response.setStatus(...), instead of response.sendError(...).
So just call:
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论