Search code examples
javajsphttp-status-code-400

How to "throw" a Bad Request from a JSP


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?


Solution

  • 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 face IllegalStateExceptions. 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.