views:

237

answers:

3

I use a javaBean in my jsp-application to store form values. This is how I get my values into my bean. This code is part of my form.jsp

try {  
        <jsp:setProperty name="formparam" property="*" />  
}  
catch (Exception e){ error = true; }

I left the "<%" out to not break the code display on stackoverflow. Now I get my exception if for example one puts text in my age field so the type conversation throws an exception.

Now I would like to know if it is possible to throw an exception in the setter of my bean an catch it with the very same try-catch-block.

Example form my bean: (I know this doesn't even compile but I hope you get an idea of what I want)

public void setAge(int a) {  
    if (this.validAge(a))  
        age = a;  
    else  
        throw Exception;  
}

I hope I get my point across. Of cause it's possible to call the validAge()-function in my bean from the form.jsp to validate the value but if I could throw an Exception directly so that the form.jsp can catch it it would be so much slicker.

So long. mantuko

A: 

1) declare the exception to be thrown 2) "throw new Exception"

public void setAge(int a) throws Exception {
  if (this.validAge(a))
    age =a ;
  else 
    throw new Exception("...")
}
Trever Shick
Damn I just missed the "throws Exception" part. Thx. This works well for me.To clarify my situation a bit:I am working on a task for my WebEngineering class and I'm just at the beginning. So I can't use JavaScript for validation because I am about to learn JSP. We don't use JSLT (whatever this is I'll read later :) ) and I just know that taglibs exist but I just don't know what they do and how to use them yet. So BalusC's answer is above my knowledge.I came to my mind that scriptlets are probably not the way to go. But up to now I have no alternative.Thx to everybody.
mantuko
+4  A: 

Just let the method throw it and use the JSTL c:catch to handle it.

<c:catch var="error">
    <jsp:setProperty name="formparam" property="*" />
</c:catch>

<c:if test="${not empty error}">
    <p>Error: ${error}</p>
</c:if>

That said, the JSP is the wrong place to do the validations. Rather submit the form to a Servlet, let the servlet delegate a business/action model which does the validation, collect all error messages in some sort of Map in request scope which you access in EL. Do in no way use scriptlets in JSP. JSTL provides pretty everything you need in the core, fmt and function taglibs.

BalusC
A: 

I'd prefer JavaScript validation methods associated with the onblur event for that text box. Let JavaScript manage this for you, not Java Beans.

duffymo