[英]How to “throw” a Bad Request from a JSP
I have a very simple JSP file, which more or less displays a get variable. 我有一个非常简单的JSP文件,该文件或多或少显示了一个get变量。
<p>Hello, <%= request.getParameter("name") %></p>
So, if I go to webpage.jsp?name=Alice
, I'd get Hello, Alice
. 因此,如果我转到
webpage.jsp?name=Alice
,我会得到Hello, Alice
。 If I just go to webpage.jsp
on the other hand, I get Hello, null
. 另一方面,如果我只是转到
webpage.jsp
, webpage.jsp
显示Hello, null
。
If the name variable is not set, I would like to send a Bad Request instead. 如果未设置name变量,我想发送一个错误请求。 In a servlet I'd do this:
在servlet中,我可以这样做:
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
How can I do similarly from a JSP page? 如何从JSP页面进行类似的操作?
Just put the same code inside <% %>
in JSP. 只需将相同的代码放在JSP的
<% %>
中。 You only need to ensure that the response isn't committed at that point, otherwise you would only face IllegalStateException
s. 您只需要确保此时未提交响应即可,否则您将只面临
IllegalStateException
。 So it should preferably be invoked on the very top of the JSP file, before all that HTML template content is emitted. 因此,最好在所有HTML模板内容发出之前在JSP文件的最顶部调用它。
Needless to say, a JSP is not the right place to control the request/response. 不用说,JSP 不是控制请求/响应的正确位置。 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.
在这种特殊情况下,如果涉及会话范围的登录,则希望在servlet或过滤器中完成该工作。 Further, that "Hello" line is better to be done as
<p>Hello, <c:out value="${param.name}" /></p>
. 此外,最好使用
<p>Hello, <c:out value="${param.name}" /></p>
来完成“ Hello”行。 It not only improves maintainability, but it also prevents your site from a huge XSS attack hole. 它不仅可以提高可维护性,而且还可以防止您的站点遭受巨大的XSS攻击漏洞。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.