如何“扔”来自 JSP 的错误请求
我有一个非常简单的 JSP 文件,它或多或少地显示了一个 get 变量。
<p>Hello, <%= request.getParameter("name") %></p>
因此,如果我访问 webpage.jsp?name=Alice
,我会得到 Hello, Alice
。另一方面,如果我只是访问 webpage.jsp
,我会得到 Hello, null
。
如果未设置名称变量,我想发送一个错误请求。在 servlet 中我会这样做:
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
How can I do from a JSP page?
I have a very simple JSP file, which more or less displays a get variable.
<p>Hello, <%= request.getParameter("name") %></p>
So, if I go to webpage.jsp?name=Alice
, I'd get Hello, Alice
. If I just go to webpage.jsp
on the other hand, I get Hello, null
.
If the name variable is not set, I would like to send a Bad Request instead. In a servlet I'd do this:
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
How can I do similarly from a JSP page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将相同的代码放入 JSP 中的
<% %>
中即可。您只需确保此时未提交响应,否则您只会面临IllegalStateException
。因此,最好在发出所有 HTML 模板内容之前在 JSP 文件的最顶部调用它。不用说,JSP 不是控制请求/响应。在这种特殊情况下,您希望在 servlet 或 过滤(如果涉及会话范围登录)。此外,“Hello”行最好写成
Hello,
。它不仅提高了可维护性,还可以防止您的网站遭受巨大的 XSS 攻击漏洞。
Just put the same code inside
<% %>
in JSP. You only need to ensure that the response isn't committed at that point, otherwise you would only faceIllegalStateException
s. So it should preferably be invoked on the very top of the JSP file, before all that HTML template content is emitted.Needless to say, a JSP is not the right place to control the request/response. In this particular case, you'd like to do the job in a servlet or perhaps a filter if it concerns a session wide login. Further, that "Hello" line is better to be done as
<p>Hello, <c:out value="${param.name}" /></p>
. It not only improves maintainability, but it also prevents your site from a huge XSS attack hole.