Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop processing a JSP early?

Tags:

java

jsp

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

like image 358
Edan Maor Avatar asked Sep 28 '09 13:09

Edan Maor


People also ask

Why is the first request to the JSP page the slowest?

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.

How do I Precompile JSPs?

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.

What is the JSP life cycle?

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.


3 Answers

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.

like image 107
Brian Agnew Avatar answered Oct 13 '22 18:10

Brian Agnew


Since 2.0, there is a standard way:

throw new javax.servlet.jsp.SkipPageException();
like image 43
daifei Avatar answered Oct 13 '22 19:10

daifei


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.

like image 21
Amit Upadhyay Avatar answered Oct 13 '22 18:10

Amit Upadhyay