2

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?

Svish
  • 152,914
  • 173
  • 462
  • 620

1 Answers1

4

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Couldn't get the c:out stuff to work, but changed it to `<%= StringEscapeUtils.escapeHtml(request.getParameter("cid")) %>`, which hopefully does the job as well :) – Svish Oct 26 '11 at 15:07
  • Just install JSTL (if your container doesn't support it) and declare `c` taglib. For installation and declaration details see also our JSTL wiki page: http://stackoverflow.com/tags/jstl/info (I hope you noticed the Servlet and Filter wiki page links in my answer as well?) – BalusC Oct 26 '11 at 15:08