Reputation: 143
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
Upvotes: 3
Views: 4945
Reputation: 308743
I'd prefer JavaScript validation methods associated with the onblur event for that text box. Let JavaScript manage this for you, not Java Beans.
Upvotes: 0
Reputation: 1108632
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.
Upvotes: 4
Reputation: 1784
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("...")
}
Upvotes: 1