6

I've got a JSP page, which calls a function and checks its return value. If the return value is not null, the JSP page goes on to use it. If the return value IS null, I want the processing of the JSP page to stop (this is because the function will perform a redirect before returning the null object. Also, the rest of the JSP code obviously uses this object, and will get a null pointer exception if the function returned null).

So my question is, what is the right way of stopping the load of a JSP page? Can I do something like this:

if (Func() == null) { return; }

Or is using a return in the middle of a JSP not the cleaner way to go about this?

Thanks

Edan Maor
  • 9,772
  • 17
  • 62
  • 92

5 Answers5

6

Since 2.0, there is a standard way:

throw new javax.servlet.jsp.SkipPageException();
daifei
  • 81
  • 1
  • 4
5

Regardless of how to terminate processing of a JSP early, I would suggest handling flow control in a servlet prior to handling the display, and switch to an appropriate JSP depending on the outcome of the function call.

I tend to use JSPs purely for displaying the contents of a bean (or more than one), and all logic is contained within the invoking servlet. By doing this you get a much cleaner separation of concerns between your components, and a more easily comprehensible and debuggable system.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 1
    This would probably be the best thing to do, but I can't change the current architecture of the project I'm working on (not worth the time right now). – Edan Maor Sep 28 '09 at 19:30
  • -1 good advice but I'm currently in a legacy code situation where modifying the servlet is out of the question (at least for the short term). Would be good to have an alternative – Josh Johnson Oct 01 '20 at 16:03
3

Brian's answer is a good advice, but it does not answer the question clearly.

The answer is YES. Bulk of JSP is converted to a method _jspService, which is being run when JSP is "executed", and since it is a regular function, that does cleanup in finally block, it is safe to return.

Amit Upadhyay
  • 237
  • 3
  • 8
2

If you really really want to do this I would suggest something like the following


..some jsp..
<%
   if (iWantToKeepProcessing) {
%>
..someother stuff..

<%
}
%>

I have to agree with Brian though and say that you should avoid entering the JSP if possible. This might not be available to you if you are handling a post/get directly targeting a dynamic JSP file rather than a controller/servlet.

Shaun
  • 4,057
  • 7
  • 38
  • 48
0

You may use JSTL tag:

<c:if test="condition">
   bodytext
</c:if>

Which is better than <% if(condition) { %> bodytext <% } %> for controlling on loading page / process.

gajesh
  • 5
  • 2