views:

648

answers:

3

I hava a url such as search.do?offset=20

offset sometimes is in the url sometimes not. When it is not in the URL i want it to be 0.

i try, without success, to retrieve the value with a scriptlet as follows:

<%  Integer offset = (pageContext.findAttribute("offset")==null) ? new Integer("0") : new Integer((String) pageContext.findAttribute("offset")); %>

Anyone knows what i am doing wrong?

+2  A: 

You should use this instead.

<% Integer offset = request.getParameter("offset") != null && request.getParameter("offset").length() > 0 ? new Integer(request.getParameter("offset")) : new Integer(0) %>

Be careful because if "offset" parameter has an incorrect integer representation a NumberFormatException will be thrown.

This is basic JSP. You could use Struts or other J2EE framework that make these conversions safer for you.

Fernando Miguélez
A: 

Fernando Miguélez expression did the work. Just a ; was missing. This is correct.

<% Integer offset = request.getParameter("offset") != null && request.getParameter("offset").length() > 0 ? new Integer(request.getParameter("offset")) : new Integer(0); %>
Sergio del Amo
A: 

I use struts but i only work with offset in the view layer since it is a pure view variable.

What did you mean with safer conversions with Struts?

Sergio del Amo
What I mean is that Struts usually hides all those conversions, since you don't access to form parameters but ActionForms. In these ActionForm beans you access native types, since Struts performs all conversions/checks for you.
Fernando Miguélez