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
The first time when you open a JSP the compiler compiles the code and creates a class file. Thats why initially when you open the JSP for the first time it takes a little longer. Thats why initially when you open the JSP for the first time it takes a little longer.
Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile. Why it is mentioned as pre compile instead of compilation is that, the request is not served. That is, the JSP will not be executed and the request will not be serviced.
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
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.
Since 2.0, there is a standard way:
throw new javax.servlet.jsp.SkipPageException();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With