JSF 2.0 - Validators

Do JSF 2.0 Validators get fired if the input is null?

JSF 2.0 is going to require a minimum of Servlet 2.5/JSP 2.1.
Edited by: rlubke on Mar 17, 2009 12:53 PM

Similar Messages

  • ANNOUNCE:  Martin Marinschek on MyFaces 2.0, IRIAN, and Related Topics

    Hello,
    In this podcast, JSFCentral editor-in-chief Kito D. Mann talks with Martin Marinschek about MyFaces, IRIAN, and related topics. This interview was recorded in December of 2009 at the JSF Summit conference in Orlando, Florida. Here is an excerpt:
    Kito: Let’s talk a little bit about the project. MyFaces was originally just an implementation but now it has grown into a very large set of projects. Tell us a bit about some of the different projects that are part of the MyFaces umbrella.
    Martin: I hope I don’t miss anything. Of course there is the core MyFaces implementation and API. For the JSF implementation you have to do the API and the Impl, so it is actually two jars which are developed in the core section. Then there are the three component libraries: Trinidad, Tomahawk, and Tobago. Then there is Orchestra, which is a conversation scope implementation for long running conversations with integration to JPA as well. Then there is the JSF Portlet Bridge, and there is ExtVal validation integration for JSF, where you can put annotations on your managed beans and domain objects. It will directly be converted into JSF converters and validators, pretty nicely done. Now that bean validation has been standardized, it is also an implementation of bean validation, so you can use the bean validation annotations together with ExtVal.
    Read the full article here: http://www.jsfcentral.com/articles/marinschek-03-10.html
    Kito D. Mann -- Author, JavaServer Faces in Action
    http://twitter.com/kito99  http://twitter.com/jsfcentral
    http://www.virtua.com - JSF/Java EE consulting, training, and mentoring
    http://www.JSFCentral.com - JavaServer Faces FAQ, news, and info
    +1 203-404-4848 x3

    We are pleased to announce that Target Management 3.0M5 is available for
    download.
    News for Users include
    * UI for viewing and changing file permissions and owner on UNIX
    * SSH Keepalive mechanism
    * Link with Editor action fixed
    * Ctrl+Space Field Assist for history in the Terminal input field
    On the internals, TM 3.0M5 provides faster startup and reduced footprint
    thanks to improved lazy loading of filter pools; and the SystemRegistry
    implementation has moved to non-UI plugins for improved UI/Non-UI
    Separation.
    See the build notes for more information:
    http://download.eclipse.org/dsdp/tm/downloads/drops/S-3.0M5- 200802181400/
    As always, the build is available for download and on the TM milestone
    update site, and will be on the Ganymede Update Site soon.
    Enjoy!
    Martin Oberhuber
    Wind River Systems, Inc.
    Target Management Project Lead, DSDP PMC Member
    http://www.eclipse.org/dsdp/tm

  • Avoiding f:convertDateTime/af:convertDateTime override

    Hi,
    According to http://www.oracle.com/webapps/online-help/jdeveloper/10.1.3/state/content/navId.4/navSetId._/vtTopicFile.jsf_apps%7Cadfcreate%7Caf_aconvertdatetimetag~html/
    ADF overrides the Date converter ID so calls to f:convertDateTime call af:convertDateTime instead. I want to undo this override because the ADF date/time converter throws up intrusive error popups if the item doesn't parse when all I really want is a tasteful error message displayed by the control. Stock JSF converters and validators do this, but ADF is forcing me to use its.
    How can I do this?
    Thanks

    No. I'm using EJB3.0. I'm not sure what you mean by having a date format set at the entity object. How would I go about that?
    I have a date format set in my selectInputDate, which works nicely, so when I select a date from the popup it will correctly enter say "01-JAN-07" into the box. But when I click submit, it gives me a date validation error, because it is validating against my locale (I think). I just need to know how to specify the date pattern to the validation routine. Do I need to write my own converter? This is my selectInputDate:
    <af:selectInputDate value="#{bindings.dateRequired.inputValue}"
    label="#{field_labels[\'HardwareRequest.dateRequired\']}"
    required="#{bindings.dateRequired.mandatory}"
    columns="#{bindings.dateRequired.displayWidth}"
    binding="#{backing_app_smurf_HardwareRequestNew.inputText4}"
    id="inputText4">
    <af:validator binding="#{bindings.dateRequired.validator}"/>
    <af:convertDateTime pattern="#{format.date}"/>
    </af:selectInputDate>
    Am I the only one that thinks using JDeveloper is like playing with Russian dolls?
    R

  • Validators - JSF 1.0 Final

    Hi
    I'm getting the following exception
    Mar 8, 2004 9:22:08 AM com.sun.faces.lifecycle.ProcessValidationsPhase execute
    SEVERE: validateDate: com.eaac.jsf.FacesValidations.validateDate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
    javax.faces.el.MethodNotFoundException: validateDate: com.eaac.jsf.FacesValidations.validateDate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
         at com.sun.faces.el.MethodBindingImpl.method(MethodBindingImpl.java:206)
         at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:124)
         at javax.faces.component.UIInput.validate(UIInput.java:733)
         at javax.faces.component.UIInput.executeValidate(UIInput.java:796)
         at javax.faces.component.UIInput.processValidators(UIInput.java:412)
         at javax.faces.component.UIForm.processValidators(UIForm.java:165)
         at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:905)
         at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:341)
         at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:78)
         at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:286)
    This was working happily with the 1.0 Beta version
    Any ideas ??

    Some more info - in my FacesValidations class
    Which is an application scoped managedBean
    public class FacesValidations
         public static void validateDate(FacesContext context, UIInput toValidate)

  • Using container managed form-based security in JSF

    h1. Using container managed, form-based security in a JSF web app.
    A Practical Solution
    h2. {color:#993300}*But first, some background on the problem*{color}
    The Form components available in JSF will not let you specify the target action, everything is a post-back. When using container security, however, you have to specifically submit to the magic action j_security_check to trigger authentication. This means that the only way to do this in a JSF page is to use an HTML form tag enclosed in verbatim tags. This has the side effect that the post is not handled by JSF at all meaning you can't take advantage of normal JSF functionality such as validators, plus you have a horrible chimera of a page containing both markup and components. This screws up things like skinning. ([credit to Duncan Mills in this 2 years old article|http://groundside.com/blog/DuncanMills.php?title=j2ee_security_a_jsf_based_login_form&more=1&c=1&tb=1&pb=1]).
    In this solution, I will use a pure JSF page as the login page that the end user interacts with. This page will simply gather the input for the username and password and pass that on to a plain old jsp proxy to do the actual submit. This will avoid the whole problem of having to use verbatim tags or a mixture of JSF and JSP in the user view.
    h2. {color:#993300}*Step 1: Configure the Security Realm in the Web App Container*{color}
    What is a container? A container is basically a security framework that is implemented directly by whatever app server you are running, in my case Glassfish v2ur2 that comes with Netbeans 6.1. Your container can have multiple security realms. Each realm manages a definition of the security "*principles*" that are defined to interact with your application. A security principle is basically just a user of the system that is defined by three fields:
    - Username
    - Group
    - Password
    The security realm can be set up to authenticate using a simple file, or through JDBC, or LDAP, and more. In my case, I am using a "file" based realm. The users are statically defined directly through the app server interface. Here's how to do it (on Glassfish):
    1. Start up your app server and log into the admin interface (http://localhost:4848)
    2. Drill down into Configuration > Security > Realms.
    3. Here you will see the default realms defined on the server. Drill down into the file realm.
    4. There is no need to change any of the default settings. Click the Manage Users button.
    5. Create a new user by entering username/password.
    Note: If you enter a group name then you will be able to define permissions based on group in your app, which is much more usefull in a real app.
    I entered a group named "Users" since my app will only have one set of permissions and all users should be authenticated and treated the same.
    That way I will be able to set permissions to resources for the "Users" group that will apply to all users that have this group assigned.
    TIP: After you get everything working, you can hook it all up to JDBC instead of "file" so that you can manage your users in a database.
    h2. {color:#993300}*Step 2: Create the project*{color}
    Since I'm a newbie to JSF, I am using Netbeans 6.1 so that I can play around with all of the fancy Visual Web JavaServer Faces components and the visual designer.
    1. Start by creating a new Visual Web JSF project.
    2. Next, create a new subfolder under your web root called "secure". This is the folder that we will define a Security Constraint for in a later step, so that any user trying to access any page in this folder will be redirected to a login page to sign in, if they haven't already.
    h2. {color:#993300}*Step 3: Create the JSF and JSP files*{color}
    In my very simple project I have 3 pages set up. Create the following files using the default templates in Netbeans 6.1:
    1. login.jsp (A Visual Web JSF file)
    2. loginproxy.jspx (A plain JSPX file)
    3. secure/securepage.jsp (A Visual Web JSF file... Note that it is in the sub-folder named secure)
    Code follows for each of the files:
    h3. {color:#ff6600}*First we need to add a navigation rule to faces-config.xml:*{color}
        <navigation-rule>
    <from-view-id>/login.jsp</from-view-id>
            <navigation-case>
    <from-outcome>loginproxy</from-outcome>
    <to-view-id>/loginproxy.jspx</to-view-id>
            </navigation-case>
        </navigation-rule>
    NOTE: This navigation rule simply forwards the request to loginproxy.jspx whenever the user clicks the submit button. The button1_action() method below returns the "loginproxy" case to make this happen.
    h3. {color:#ff6600}*login.jsp -- A very simple Visual Web JSF file with two input fields and a button:*{color}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
        <jsp:directive.page
    contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"/>
        <f:view>
            <webuijsf:page
    id="page1">
    <webuijsf:html id="html1">
    <webuijsf:head id="head1">
    <webuijsf:link id="link1"
    url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body id="body1" style="-rave-layout: grid">
    <webuijsf:form id="form1">
    <webuijsf:textField binding="#{login.username}"
    id="username" style="position: absolute; left: 216px; top:
    96px"/>
    <webuijsf:passwordField binding="#{login.password}" id="password"
    style="left: 216px; top: 144px; position: absolute"/>
    <webuijsf:button actionExpression="#{login.button1_action}"
    id="button1" style="position: absolute; left: 216px; top:
    216px" text="GO"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
            </webuijsf:page>
        </f:view>
    </jsp:root>h3. *login.java -- implent the
    button1_action() method in the login.java backing bean*
        public String button1_action() {
            setValue("#{requestScope.username}",
    (String)username.getValue());
    setValue("#{requestScope.password}", (String)password.getValue());
            return "loginproxy";
        }h3. {color:#ff6600}*loginproxy.jspx -- a login proxy that the user never sees. The onload="document.forms[0].submit()" automatically submits the form as soon as it is rendered in the browser.*{color}
    {code}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    version="2.0">
    <jsp:output omit-xml-declaration="true" doctype-root-element="HTML"
    doctype-system="http://www.w3.org/TR/html4/loose.dtd"
    doctype-public="-W3CDTD HTML 4.01 Transitional//EN"/>
    <jsp:directive.page contentType="text/html"
    pageEncoding="UTF-8"/>
    <html>
    <head> <meta
    http-equiv="Content-Type" content="text/html;
    charset=UTF-8"/>
    <title>Logging in...</title>
    </head>
    <body
    onload="document.forms[0].submit()">
    <form
    action="j_security_check" method="POST">
    <input type="hidden" name="j_username"
    value="${requestScope.username}" />
    <input type="hidden" name="j_password"
    value="${requestScope.password}" />
    </form>
    </body>
    </html>
    </jsp:root>
    {code}
    h3. {color:#ff6600}*secure/securepage.jsp -- A simple JSF{color}
    target page, placed in the secure folder to test access*
    {code}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
    <jsp:directive.page
    contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"/>
    <f:view>
    <webuijsf:page
    id="page1">
    <webuijsf:html id="html1">
    <webuijsf:head id="head1">
    <webuijsf:link id="link1"
    url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body id="body1" style="-rave-layout: grid">
    <webuijsf:form id="form1">
    <webuijsf:staticText id="staticText1" style="position:
    absolute; left: 168px; top: 144px" text="A Secure Page"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
    </webuijsf:page>
    </f:view>
    </jsp:root>
    {code}
    h2. {color:#993300}*_Step 4: Configure Declarative Security_*{color}
    This type of security is called +declarative+ because it is not configured programatically. It is configured by declaring all of the relevant parameters in the configuration files: *web.xml* and *sun-web.xml*. Once you have it configured, the container (application server and java framework) already have the implementation to make everything work for you.
    *web.xml will be used to define:*
    - Type of security - We will be using "form based". The loginpage.jsp we created will be set as both the login and error page.
    - Security Roles - The security role defined here will be mapped (in sun-web.xml) to users or groups.
    - Security Constraints - A security constraint defines the resource(s) that is being secured, and which Roles are able to authenticate to them.
    *sun-web.xml will be used to define:*
    - This is where you map a Role to the Users or Groups that are allowed to use it.
    +I know this is confusing the first time, but basically it works like this:+
    *Security Constraint for a URL* -> mapped to -> *Role* -> mapped to -> *Users & Groups*
    h3. {color:#ff6600}*web.xml -- here's the relevant section:*{color}
    {code}
    <security-constraint>
    <display-name>SecurityConstraint</display-name>
    <web-resource-collection>
    <web-resource-name>SecurePages</web-resource-name>
    <description/>
    <url-pattern>/faces/secure/*</url-pattern>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
    <http-method>HEAD</http-method>
    <http-method>PUT</http-method>
    <http-method>OPTIONS</http-method>
    <http-method>TRACE</http-method>
    <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
    <description/>
    <role-name>User</role-name>
    </auth-constraint>
    </security-constraint>
    <login-config>
    <auth-method>FORM</auth-method>
    <realm-name/>
    <form-login-config>
    <form-login-page>/faces/login.jsp</form-login-page>
    <form-error-page>/faces/login.jsp</form-error-page>
    </form-login-config>
    </login-config>
    <security-role>
    <description/>
    <role-name>User</role-name>
    </security-role>
    {code}
    h3. {color:#ff6600}*sun-web.xml -- here's the relevant section:*{color}
    {code}
    <security-role-mapping>
    <role-name>User</role-name>
    <group-name>Users</group-name>
    </security-role-mapping>
    {code}
    h3. {color:#ff6600}*Almost done!!!*{color}
    h2. {color:#993300}*_Step 5: A couple of minor "Gotcha's"_ *{color}
    h3. {color:#ff6600}*_Gotcha #1_*{color}
    You need to configure the "welcome page" in web.xml to point to faces/secure/securepage.jsp ... Note that there is *_no_* leading / ... If you put a / in there it will barf all over itself .
    h3. {color:#ff6600}*_Gotcha #2_*{color}
    Note that we set the <form-login-page> in web.xml to /faces/login.jsp ... Note the leading / ... This time, you NEED the leading slash, or the server will gag.
    *DONE!!!*
    h2. {color:#993300}*_Here's how it works:_*{color}
    1. The user requests the a page from your context (http://localhost/MyLogin/)
    2. The servlet forwards the request to the welcome page: faces/secure/securepage.jsp
    3. faces/secure/securepage.jsp has a security constraint defined, so the servlet checks to see if the user is authenticated for the session.
    4. Of course the user is not authenticated since this is the first request, so the servlet forwards the request to the login page we configured in web.xml (/faces/login.jsp).
    5. The user enters username and password and clicks a button to submit.
    6. The button's action method stores away the username and password in the request scope.
    7. The button returns "loginproxy" navigation case which tells the navigation handler to forward the request to loginproxy.jspx
    8. loginproxy.jspx renders a blank page to the user which has hidden username and password fields.
    9. The hidden username and password fields grab the username and password variables from the request scope.
    10. The loginproxy page is automatically submitted with the magic action "j_security_check"
    11. j_security_check notifies the container that authentication needs to be intercepted and handled.
    12. The container authenticates the user credentials.
    13. If the credentials fail, the container forwards the request to the login.jsp page.
    14. If the credentials pass, the container forwards the request to *+the last protected resource that was attempted.+*
    +Note the last point! I don't know how, but no matter how many times you fail authentication, the container remembers the last page that triggered authentication and once you finally succeed the container forwards your request there!!!!+
    +The user is now at the secure welcome page.+
    If you have read this far, I thank you for your time, and I seriously question your ability to ration your time pragmatically.
    Kerry Randolph

    If you want login security on your web app, this is one way to do it. (the easiest way i have seen).
    This method allows you to create a custom login form and error page using JSF.
    The container handles the actual authentication and protection of the resources based on what you declare in web.xml and sun-web.xml.
    This example uses a statically defined user/password, stored in a file, but you can also configure JDBC realm in Glassfish, so that that users can register for access and your program can store the username/passwrod in a database.
    I'm new to programming, so none of this may be a good practice, or may not be secure at all.
    I really don't know what I'm doing, but I'm learning, and this has been the easiest way that I have found to add authentication to a web app, without having to write the login modules yourself.
    Another benefit, and I think this is key ***You don't have to include any extra code in the pages that you want to protect*** The container manages this for you, based on the constraints you declare in web.xml.
    So basically you set it up to protect certain folders, then when any user tries to access pages in that folder, they are required to authenticate.
    --Kerry                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • A new approach to JSF error handling?

    Hi.
    I would like to run an idea by the community to check that I am not being crazy in doing this stuff. I would appreciate any comments, criticism or ideas.
    I was thinking about JSF's error processing mechanism, specifically about how label text gets associated with an input field. So, I am talking about this kind of stuff:
    <h:outputLabel for="firstName" value='#{msgs["applicant.search.firstName"]}: ' />
    <h:inputText id="firstName" value='#{applicantDetailsBackingBean.firstName}' required=�true�/>If the value is not entered into the input field, we will get an error message saying:
    �First Name�: is required.
    So HtmlMessageRenderer has replaced the field id in the FacesMessage with the label text by using the association set up with the 'for' attribute on the label. All of this message "decoration" work happens in the RENDER phase in a centralized location. I see a couple of weaknesses in this approach
    1) It is too late for resolving label text data if the label is inside a data table
    2) JSF establishes associations between label text and the input fields by using the label components to point to their input fields. Although this seems more natural, it limits label text sources to just the label components present on the current page (or whatever is nested under them), which makes it impossible to associate input field messages with label text that does not exist on the page in its entirety.
    Let's look at a couple examples, both of which I ran into in my application:
    1) Consider a situation in which we have a dataTable where every row consists of a student name and an input field for entering their assignment mark. The validation on the input field will be restricted to valid letter grades only. If the user enters an invalid grade, we want them to see an error message of the form: +�The mark entered for <student name> is invalid�.+ Since <student name> is dependent on the row in which the error occurred, this error message is not possible to generate with bare JSF functionality.
    2) Another situation that gets us in trouble is when the label text we want in our error message is not on the page (or not in it's entirety). For example, your page could be split up into multiple parts with those parts having input fields with the same name. We would want the error message to include the page part as well as the field name. This is not easily achieved with the bare JSF functionality.
    So to generalize, any situation where a label component with a static value throughout the lifecycle is not available will cause difficulty.
    Please correct me if I am wrong on any of these points.
    Since in my app I had a lot of complicated pages to deal with, I solved my difficulties by writing a very simple framework that I called Message Decorator Framework (MDF). It enabled me to easily construct much more detailed error messages than what the standard JSF approach seems to allows for. MDF provides a mechanism to specify the label text to be applied to a validation or a conversion message by either a literal, an el expression or via an id of another ValueHolder and all of these work in data tables.
    The idea is a s such, and this is what i would like your opinion on:
    MDF provides more flexible message decoration by adapting the opposite approach to the one used by the JSF:
    1) Message decoration is decentralized. MDF wraps converters and validators on individual input fields and performs message text replacement right on the spot in the PROCESS_VALIDATIONS phase, when all of the pertinent data for resolving the label text is still available.(i.e the components in data tables would still have the correct values for the current row being validated)
    2) The label text to be used is specified by the input field, not the label. This allows the developer to reference any text value, instead of tying them to a specific label component.
    Pictures are better than words, so here is an architectural diagram:
    http://www.imagehosting.com/out.php/i1259440_ArchitectureDiagram.png
    The framework consists of two main classes, ConverterMessageDecorator and ValidatorMessageDecorator. I will just talk about the converter part, b/c the validator part is very similar but wraps a list of validators instead of one converter.
    So ConverterMessageDecorator is a JSF converter. Its purpose is to wrap the converter that is going to do the actual conversion work and decorate the FacesMessage inside ConverterException if one was thrown.
    The converter to wrap can be either determined automatically based on the type of the value reference of the input field or specified explicitly. This converter decorates the message by replacing all instances of the input field�s id with the resolved label text. The power of this approach is that not only do you get a much more flexible way to specify what the label text is (either fieldLabel or fieldLabelComponent attributes), but now data tables are no longer a problem.
    Here are some usage examples:
    <h:inputText value='#{section33SetupBackingBean.contribution.sampleGatePct}'>
       <md:decorateConverterMessage fieldLabel= '#{msgs["section.34.setup.contribution.initial.sampling.gate.max.size"]}' />
    </h:inputText>
    �etc�
    <h:inputText value='#{section33SetupBackingBean.payment.sampleGatePct}'>
       <md:decorateConverterMessage fieldLabel= '#{msgs["section.34.setup.payment.initial.sampling.gate.max.size"]}' />
    </h:inputText>The two input fields have exactly the same labels on the screen (they are in two different parts of the page), so if we used their respective labels, the error messages would look the same for these two input fields.
    More complicated example:
    <h:dataTable value="#{paymentCalcBackingBean.currentPaymentPercentages}" var="currentPercentage" >
    <h:column>
      <ops:refDataDescription id="provinceLabelTextId" refDataType="provinceStateType"
                code="${currentPercentage.programProvince.provinceStateTypeCode}" />
    </h:column>
    <h:column>
      <h:inputText value="${currentPercentage.federalPercentage}">
    <md:decorateConverterMessage fieldLabelComponent="provinceLabelTextId"  valueRequired="true" >
       <f:converter converterId="ops.PercentageConverter" />
    </md:decorateConverterMessage>
    <md:decorateValidatorMessage fieldLabelComponent="provinceLabelTextId" >
       <f:validator validatorId="ops.PercentageValidator" />
    </md:decorateValidatorMessage>
    </h:column>
    �etc�
    </h:dataTable>This would produce errors shown in this screenshot: http://www.imagehosting.com/out.php/i1259418_Example3.png
    Here is another example that shows off what you can do by referencing other ValueHolders on the page.
    The code is exactly the same as the snippet shown above, but the inputText component is referencing a text box, so the label text is going to be whatever the user types into the text box:
    http://www.imagehosting.com/out.php/i1259467_Example4.png
    Does this approach seem reasonable to people, or am I reinventing the wheel? Please let me know.
    Val

    Try restarting the DTR application and see if the problem persists.

  • Creating Custom Validators for ADF in JDev 10.1.3.1

    Hi all,
    I'm trying to create a validator to solve a seemingly common problem - that is given 2 dates (startDate & endDate), validate that endDate cannot be earlier than startDate.
    In my case, both startDate and endDate are in the same form. From the ADF Developers Guide, the recommended approach is to create the validation method on the page's backing bean. But in my application, there are many occurrences of startDate and endDate in other forms, therefore having the validation method on the backing bean might not be the best solution.
    I tried to create my own custom validator and tying it to a tag library stated in http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSFDevelop6.html#wp999130, but that didn't seem to work either. I'm not sure if creating custom validators by extending the ValidatorTag is supported in ADF.
    Would appreciate it if someone has any suggestions on how to create the validator that I need, without having validation methods that does the same thing all over my backing beans.
    TIA.
    Regards,
    Lennard

    Hi,
    of course, ADF Faces supports custom validators because it is compliant to the JSF APIs runnting on the JSF RI.
    Another approach for validation would be on the business service level. Assuming you use ADF BC, the EO can have a method validator defined that is automatically inherited by all its views. The disadvantage though is that the error message would have to come from the server, requiring custom error message handling for user friendly messages as described in the developer guide.
    Looking forward, in a next release of ADF the binding ayer will allow more complex validations thus not requiring to handle complex validation on teh business service.
    So far however I think that using a custom validator is the best you can do. Note that in the case of ADF BC the date is of type oracle.jbo.server.domain.Date and not java.util.Date, which might be a hint to check for your validator issue
    Frank

  • Custom error messages impossible with jsf ea4??

    Hello,
    Does jsf allow custom error messages for built-in validators?
    I was told by a member of the jsf team that what is described in the tutorial applies only to future versions of jsf.
    Is this a bug? If it isn't and if it is indeed possible to have your own error messages for built-in validators, I would be grateful for someone of the jsf team to help me.
    I have already posted some messages asking for help but I never got any answer.
    Julien

    If a validator wants to add an error message to the current page, it has to call FacesContext.addMessage() with a javax.faces.application.Message argument. The design intent is that you can look up localized messages (defined in the config file) via MessageResources -- that's the part that does not work right now.
    In the interim, though, you can construct your own Message instances by leveraging the MessageImpl class:
    context.addMessage
    (new MessageImpl(Message.SEVERITY_ERROR,
    "You goofed",
    "Here are the gory details..."));
    or look up the message strings from a resource bundle.
    Craig

  • Problem with resource bundle messages written inside script of jsf included

    Hi,
    I have a main jsf page with the name Details.jsp.In this page I included Contacts jsf page.I am using resouce bundle for my application.I written all the output text tags with this resouce bundle keys.And I written the Details main page javascript alerts with this resource bundle correctly.But the problem is,I am having script alrts in my included jsf apge i.e. in Contacts page.When I write the script alerts with the resource bundle keys,it is not displaying properly.
    ---------------------------------------------------------------------Details.jsp--------------------------------------
    <f:loadBundle basename="Details_en" var="msg"/>
    <f:view>
    <head>
    <script>
    function saveFn()
    var d=document.getElementById('dform:dinputtext').value;
    if(d=='')
    alert('<h:outputText value="#{msg.requiredValidationMsgkey}"/>');
    return false;
    if(emailValidation()==false)
    return false;
    </script>
    </head>
    <body>
    <h:form id="dform">
    <h:outputText value="#{msg.nameHeader}"/>
    <h:inputText value="#{Bean.name}" id="dinputtext"/>
    <jsp:include page="/Contacts.jsp"/>
    <h:commandButton value="Save" onclick="if(saveFn()==false) return false;" action="#{Bean.saveAction}"/>
    </h:form>
    </body>
    </f:view>
    -------------------------------------------------Contacts.jsp----------------------------------------
    <script>
    function emailValidation()
    var em= document.getElementById('dform:cSubView:cemailtext').value;
    if(em=='')
    alert('<h:outputText value="#{msg.emailValidationMsgKey}"/>');
    return false;
    </script>
    <f:subview id="cSubView">
    <h:inputText value="#{CBean.email}" id="cemailtext" />
    </f:subview>
    The alert message in SaveFn is getting appeared coorectly.But in the function emailValidation is not geting dispalyed correctly.It is appearing as normat output text in the page,but not as an alert.

    Thanks for the reply.
    But I want to do some validations using javascript not only the required validation.
    In my application 5 text fields and one command button are there .Depending upon combination of 2 or 3 text field values, I have to get the values when I pressed command button.
    If I use the h:messages for validators,the conversion error is occurring when the text field takes wrong data.So it is going to give incorrect results when I press the command button.Thats why I am using javascript.
    When user enters wrong data,I want to do validation using javascript and I want to display the alert message using resource bundle.

  • About jsf and tiles

    Good days , the following exception is happening:
    javax.faces.FacesException
    at de.mindmatters.faces.lifecycle.RenderResponsePhase.executePhase(RenderResponsePhase.java:53)
    at de.mindmatters.faces.lifecycle.AbstractPhase.execute(AbstractPhase.java:37)
    at de.mindmatters.faces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:166)
    at de.mindmatters.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:226)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:138)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:363)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:712)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:406)
    at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:211)
    at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139)
    at org.mortbay.jetty.Server.handle(Server.java:313)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:506)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:830)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:514)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:381)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396)
    at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:442)
    Caused by: java.lang.NullPointerException
    at org.apache.myfaces.tomahawk.application.jsp.JspTilesViewHandlerImpl.renderView(JspTilesViewHandlerImpl.java:168)
    at org.ajax4jsf.framework.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:101)
    at org.ajax4jsf.framework.ajax.AjaxViewHandler.renderView(AjaxViewHandler.java:221)
    at de.mindmatters.faces.lifecycle.RenderResponsePhase.executePhase(RenderResponsePhase.java:45)
    ... 21 more
    my web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <context-param>
    <param-name>com.sun.faces.verifyObjects</param-name>
    <param-value>true</param-value>
    <description>
    Set this flag to true if you want the JSF
    Reference Implementation to verify that all of the application
    objects you have configured (components, converters,
    renderers, and validators) can be successfully created.
    Default value is false.
    Poner a false cuando se ponga en produccion.
    </description>
    </context-param>
    <context-param>
    <param-name>com.sun.faces.validateXml</param-name>
    <param-value>true</param-value>
    <description>
    Set this flag to true if you want the JSF
    Reference Implementation to validate the XML in your
    faces-config.xml resources against the DTD. Default
    value is false.
    Poner a false cuando se ponga en produccion.
    </description>
    </context-param>
    <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
    <description>
    Indica donde queremos guardar el estado de la aplicacion.
    Poner a server cuando se ponga en produccion. antes probarlo!
    </description>
    </context-param>
    <context-param>
    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
    <param-value>true</param-value>
    <description>
    Este parametro le dice a MyFaces si se va a permitir renderizar javascript.
    Default: "true"
    </description>
    </context-param>
    <context-param>
    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
    <param-value>true</param-value>
    <description>
    si es verdadero, el renderizado html estara formateado, permitiendo que se pueda leer
    bien. En la fase de desarrollo, estara a true, cuando este en produccion, estara a false.
    </description>
    </context-param>
    <session-config>
    <session-timeout>
    30
    </session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>
    index.jsp
    </welcome-file>
    </welcome-file-list>
    <!-- listener de spring-->
    <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Tiles configuration
    definition files and a listener need to be defined.
    the listener will initialize JspTilesViewHandlerImpl with tiles definitions.
    -->
    <servlet>
    <servlet-name>TilesServet</servlet-name>
    <servlet-class>org.apache.struts.tiles.TilesServlet</servlet-class>
    <init-param>
    <param-name>definitions-config</param-name>
    <param-value>/WEB-INF/tiles-defs.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <filter>
    <filter-name>MyFacesExtensionsFilter</filter-name>
    <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
    </filter>
    </web-app>
    tiles-defs.xml
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE tiles-definitions PUBLIC
    "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
    "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
    <tiles-definitions>
    <definition name="Base" path="/paginas/plantillaBasica.jsp">
    <put name="titulo" value="Base" type="string"/>
    <put name="cabecera" value="/cabecera.jsp" type="page"/>
    <put name="cuerpo" value="base" type="page"/>
    <put name="pie" value="base" type="page"/>
    </definition>
    <definition name="/busquedaDosCajas.tiles" extends="Base">
    <put name="titulo" value="Busqueda con dos cajas" type="string"/>
    <put name="cuerpo" value="/paginas/cuerpoDosCajas.jsp" type="page"/>
    </definition>
    </tiles-definitions>
    faces-config.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE faces-config PUBLIC
    "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
    "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
    <!-- =========== FULL CONFIGURATION FILE ================================== -->
    <faces-config>
    <application>
    <view-handler>org.apache.myfaces.tomahawk.application.jsp.JspTilesViewHandlerImpl</view-handler>
    </application>
    <!-- El mantenimiento del bean proxy se delega al contenedor de spring-->
    <application>
    <variable-resolver>
    org.springframework.web.jsf.DelegatingVariableResolver
    </variable-resolver>
    </application>
    <!-- el unico idioma permitido es el espa�ol.-->
    <application>
    <locale-config>
    <default-locale>es</default-locale>
    </locale-config>
    </application>
    <!--
    - navigation rules
    -->
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>succesNoJS</from-outcome>
    <to-view-id>/paginas/listado.jsp</to-view-id>
    </navigation-case>
    <navigation-case>
    <from-outcome>error</from-outcome>
    <to-view-id>error.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    </faces-config>
    index.jsp
    <%@ page session="false"%>
    <%
    response.sendRedirect("busquedaDosCajas.jsf");
    %>
    anybody could help me? i dont know whats happening
    regards a lot

    first make sure you are using Tiles stand-alone (in Struts Sandbox)
    add the follwoing servlet to your web.xml
    <servlet>
    <servlet-name>Tiles Servlet</servlet-name>
    <servlet-class>org.apache.tiles.servlet.TilesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    add the following context-param to your web.xml
    <context-param>
    <param-name>tiles-definitions</param-name>
    <param-value>/WEB-INF/tiles.xml</param-value>
    </context-param>
    add the following to your faces-config.xml
    <view-handler>org.apache.shale.tiles.TilesViewHandler</view-handler>
    add the following dependency to your pom.xml
    <dependency>
    <groupId>org.apache.shale</groupId>
    <artifactId>shale-tiles</artifactId>
    <version>1.0.3</version>
    </dependency>
    that should be it.
    Khaled

  • JSF Shopping List

    Hi all....my development team has been working in a web framework for the past 8+ months and we have hit a few serious roadblocks. I'm considering spearheading a switch to JSF, but I need to know if it will meet our requirements. After a perusal of O'Reilly's JSF book, by Hans Bergen, I have a general feel, but I'm interested in your opinions & experiences--e.g., the framework we're using claims to have certain functionality, but it's clearly broken.
    Some of the items on this list have obvious answers & some are answerred in the O'Reilly book, but I'm interested in confirmation from you, the folks in the trenches.
    Thanks in advance for your help,
    - Mike
    Shopping List:
    General Items:
    - what are JSFs biggest drawbacks if I were to use it as an enterprise technology for the next 5 years?
    - what are the biggest problems with Facelets?
    - if I use Facelets, do I still have to be a JSP guru?
    - what are the best books on JSF?
    - which is better, MyFaces or RI?
    Specific Items:
    - does JSF have the ability to create a library of reusable components?
    - backwards compatibility of components as new versions are released?
    - server-side and client-side validation?
    - can I easily create custom validation components?
    - does JSF have any glaring concurrency issues?
    - can I programmatically add components to a page at run time?
    - does JSF require me to use JDK1.5, or can I use 1.4?
    - does JSF support a single application properties file for i18n?
    - does JSF support per-page properties file for i18n (that override what is in the application file)?
    - can I easily display a single page in a different language?
    - does JSF allow for page inheritence? (can I create custom sub-pages from a generic parent "SearchPage"?)

    I'll answer the things that I can. You cover quite a range with your questions though...
    - what are JSFs biggest drawbacks if I were to use
    e it as an enterprise technology for the next 5
    years?- JSF is still a young technology and will likely undergo a number of changes that will break backwards compatibility.
    - Performance could become an issue on very large applications.
    - what are the biggest problems with Facelets?- There are a number of little "got'cha's" once you start getting into it. Expect to be writing a number of custom validators and components.
    - There is a lack of control over the faces lifecycle, which can frustrate attempts to skip phases.
    - if I use Facelets, do I still have to be a JSP
    P guru?Not at all. Faces actually takes over for JSP quite nicely, especially once you realize it's full capability. However, it doesn't hurt to have minimal knowledge of JSP. Nothing more than a developer worth his salary couldn't learn in a day or two.
    - what are the best books on JSF?I like Core JavaServer Faces by David Geary and Cay Horstmann. Partial book is online:
    http://www.horstmann.com/corejsf/
    - which is better, MyFaces or RI?Hah! This could start a few wars. Honestly, haven't looked much at MyFaces but I know that it just extends the RI with some extra components. Most people who use MyFaces swear by it. However, I wrote an entire enterprise application with just the RI and my own customs. Works great!
    - does JSF have the ability to create a library of
    f reusable components?Yes, absolutely. I did this with my app and the new library will be very helpful to future projects.
    - backwards compatibility of components as new
    w versions are released?Ok... Here you might have a few problems. I've already heard rumours of JSF 1.2 breaking a lot of 1.1. I know that there were major changes between 1.0 and 1.1 too. The JSF developers do not seem to be terribly concerned with backwards compatibility.
    - server-side and client-side validation?Server-side only. You'll need to use a client-side technology (such as JavaScript) for client-side validation. However, JSF components offer JavaScript hooks, so you can easily execute functions onchange, onclick, onblur, etc...
    - can I easily create custom validation components?Easy is a relative term. =) Not always. Writing customs will require a high learning curve. How easy it is depends on what you're doing and how closely you're tying it into other pre-existing components/validators/converters. After each custom you write, it starts getting a little easier.
    - does JSF support a single application properties
    s file for i18n?I'll hazard a guess on this one, don't quote me on it. A separate message properties file is required for each locale. The message bundle will choose the appropriate one for each locale.
    - does JSF support per-page properties file for i18n
    n (that override what is in the application file)?I think not. Again, just guessing here.
    - can I easily display a single page in a different
    t language?Yes, actually this is quite easy. Assuming you set up the locale properly, you just need to use the h:outputText component with f:loadBundle to retrieve the messages.
    Hope this helps,
    CowKing

  • Integrate tomahawk into sun jsf ,extensionsFilter not correctly configured.

    Hi,All
    I find a issue when I integrate tomahawk 1.1.3 into sun jsf 1.1_02:
    tomcat 5.0.28
    java.lang.IllegalStateException: ExtensionsFilter not correctly configured. Resource mapping missing. Resources cant be delivered. Please see: http://myfaces.apache.org/tomahawk/extensionsFilter.html
    org.apache.myfaces.renderkit.html.util.AddResourceFactory.throwExtensionsFilterMissing(AddResourceFactory.java:371)
    org.apache.myfaces.renderkit.html.util.AddResourceFactory.checkEnvironment(AddResourceFactory.java:352)
    org.apache.myfaces.renderkit.html.util.AddResourceFactory.getInstance(AddResourceFactory.java:288)
    org.apache.myfaces.custom.tree2.HtmlTreeRenderer.encodeJavascript(HtmlTreeRenderer.java:611)
    I read information about it from "http://myfaces.apache.org/tomahawk/extensionsFilter.html"
    and reconfiguration my web.xml, but don't work. my code as follow:
    <!-- web.xml> -->
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    <display-name>Web Configuration Info</display-name>
    <description>Platform</description>
         <context-param>
    <param-name>javax.faces.CONFIG_FILES</param-name>
    <param-value>/WEB-INF/Config/faces-config.xml,/WEB-INF/Config/faces-managed-beans.xml,/WEB-INF/Config/faces-config-validators.xml,/WEB-INF/Config/faces-config-taglibs.xml</param-value>
    </context-param>
         <filter>
              <filter-name>ExtensionsFilter</filter-name>
              <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
              <init-param>
                   <param-name>maxFileSize</param-name>
                   <param-value>20m</param-value>
              </init-param>
         </filter>
         <filter-mapping>
         <filter-name>ExtensionsFilter</filter-name>
              <!-- servlet-name must match the name of your javax.faces.webapp.FacesServlet entry -->
              <servlet-name>FacesServlet</servlet-name>
         </filter-mapping>
         <filter-mapping>
    <filter-name>ExtensionsFilter</filter-name>
    <url-pattern>*.jsf</url-pattern>
    </filter-mapping>
    <servlet>
    <servlet-name>FacesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
              <load-on-startup>1</load-on-startup>
    </servlet>
         <servlet-mapping>
    <servlet-name>FacesServlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
         <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
         </welcome-file-list>
    </web-app>
    <!-- index.jsp -->
    <%@ page session="false" contentType="text/xml;charset=utf-8"%>
    <%
    response.sendRedirect("./test/tree.jsf");
    %>
    I write web.xml reference to extensionsFilter.html, but doesn't work!
    what's make this issue?

    I think you need the following additional mapping:
        <filter-mapping>
            <filter-name>MyFacesExtensionFilter</filter-name>
            <url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
        </filter-mapping>

  • JSF Custom Validator Problem

    Please help,
    I have written a handful of custom validators and I'm having a small problem with them. For some reason the validator will not display there message in a <h:message> tag. They do however display in a <h:messages> tag as long as the globalOnly attribute is set to false. I'm guessing this is being caused by the fact that the validators are not being registered properly with their parent components. My question is how do I accomplish registering the validator correctly with its parent component.
    Below is an example of one of the valiators and its use in the page.
    <c:form validationType="Server">
        <label>Phone Number</label>
        <h:inputText id="PhoneNumber">
         <c:validatePhoneNumber errorSummary="Please enter a valid Phone number" errorDetail="Blah"></c:validatePhoneNumber>
        </h:inputText>
        <h:message style="color: red" for="PhoneNumber" />
        <h:commandButton value="Submit"></h:commandButton>
    </c:form>
    public class PhoneNumberValidatorTag extends ValidatorTag {
      private static final long serialVersionUID = -3061371618875302020L;
      private final String validatorId = "jsf.validators.PhoneNumber";
      private String validationType;
      private String validateAgainst = PhoneNumberValidator.US;
      private String errorSummary = "";
      protected String errorDetail = "";
      public PhoneNumberValidatorTag() {
        setValidatorId( validatorId );
      public Validator createValidator() throws JspException {
        PhoneNumberValidator validator = ( PhoneNumberValidator ) super
            .createValidator( );
        FacesContext context = FacesContext.getCurrentInstance( );
        Application app = context.getApplication( );
        Util.doAssert( null != validator );
        UIComponentTag tag = UIComponentTag.getParentUIComponentTag( pageContext );
        UIComponent component = tag.getComponentInstance( );
        UIComponent parentForm = component;
        while ( !( parentForm instanceof HtmlForm ) ) {
          parentForm = parentForm.getParent( );
        ValidationHtmlForm vhf = ( ValidationHtmlForm ) ( ( HtmlForm ) parentForm );
        if ( "client".equalsIgnoreCase( vhf.getValidationType( ) ) ) {
          validator.setServerValidate( false );
        } else {
          validator.setServerValidate( true );
          if ( errorSummary != null ) {
            if ( UIComponentTag.isValueReference( errorSummary ) ) {
              validator.setErrorSummary( ( String ) app.createValueBinding(
                  errorSummary ).getValue( context ) );
            } else {
              validator.setErrorSummary( errorSummary );
          if ( validateAgainst != null ) {
            if ( UIComponentTag.isValueReference( validateAgainst ) ) {
              validator.setErrorSummary( ( String ) app.createValueBinding(
                  validateAgainst ).getValue( context ) );
            } else {
              validator.setErrorSummary( validateAgainst );
        return validator;
      public void release()
        super.release();
      public int doEndTag() throws JspException {
        FacesContext context = FacesContext.getCurrentInstance( );
        ResponseWriter writer = context.getResponseWriter( );
        try {
          UIComponentTag tag = UIComponentTag.getParentUIComponentTag( pageContext );
          UIComponent component = tag.getComponentInstance( );
          UIComponent parentForm = component;
          while ( !( parentForm instanceof HtmlForm ) ) {
            parentForm = parentForm.getParent( );
          ValidationHtmlForm vhf = ( ValidationHtmlForm ) parentForm;
          if ( "client".equalsIgnoreCase( vhf.getValidationType( ) )
              || "both".equalsIgnoreCase( vhf.getValidationType( ) ) ) {
            writer
                .write( StringUtil
                    .format(
                        "<script language='JavaScript'>"
                            + " formValidator.addValidator('{0}',new PhoneNumberValidator('{1}', PhoneNumberValidator.{2} ,'{3}'));"
                            + "</script>", new Object[] {
                            parentForm.getClientId( context ),
                            component.getClientId( context ), validateAgainst,
                            errorSummary } ) );
        } catch ( IOException e ) {
          e.printStackTrace( );
        return 1;
      � Getters and Setters removed to shorten code
    public class PhoneNumberValidator extends BaseValidator {
      private static final long serialVersionUID = -1925668990356710828L;
      public static final String US = "US";
      public static final String INTERNATIONAL = "INTERNATIONAL";
      public static HashMap REG = new HashMap( );
      static{
        REG.put( "US", "^\\(?\\d{3}\\)?(\\s|-)\\d{3}-\\d{4}$" );
        REG.put( "INTERNATIONAL",
            "^((\\+\\d(\\d)?)?(\\(\\d\\{3}?)))? \\d{3}?-\\d{4}$" );
      public PhoneNumberValidator() {
        super( );
      public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if ( !serverValidate )
          return;
        if ( value == null )
          return;
        if ( context == null || component == null )
          throw new NullPointerException( );
        String regex;
        if ( REG.containsKey( validateAgainst ) )
          regex = ( String ) REG.get( validateAgainst );
        else
          regex = ( String ) REG.get( US );
        Pattern pattern = Pattern.compile( regex );
        if ( !"".equals( value.toString( ).trim( ) )
            && !pattern.matcher( value.toString( ).trim( ) ).matches( ) ) {
          Object[] params = new Object[] { value };
          Locale locale = context.getViewRoot( ).getLocale( );
          String summary;
          if ( errorSummary == null )
            summary = Messages.getString(
                "resource.ValidationMessages", "badPhoneNumber",
                params );
          else
            summary = new MessageFormat( errorSummary, locale ).format( params );
          String detail;
          if ( errorDetail == null )
            detail = Messages.getString(
                "resource.ValidationMessages",
                "badPhoneNumber_detail", params );
          else
            detail = new MessageFormat( errorDetail, locale ).format( params );
          FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR,
              summary, detail );
          throw new ValidatorException( message );
      public String getJavaScript() {
         � Method body removed to shorten post
    }I probably should also mention I overrode the HtmlForm tag so I could add an attribute to the tag that allows the developer to specify client, server, or both when they are choosing the valiation type they want to use.
    Thank you in advance for any help you can provide.
    Grape Ape

    I do not think what you want to do is possible with the standard panelGrid. The panelGrid sees each child (of the panelGrid) as 1 component. The childrens children are considered a part of the child.
    Heh, did I confuse you with that? You have probably already guessed that though.
    At one time, I considered creating a custom component like yours. One that would just allow rendering of it's children or not. I decided that it was easier and better to add the rendered attribute to each of my other custom components (since the functionality is already supported by UIComponent). All you have to do is add the rendered attribute to your TLD doc for each custom component and your component can now use the "rendered" attribute. Oh, and you'll have to call super.setProperties() in the component tag.
    All JSF standard components can use the rendered attribute.
    Let me know if you'd like me to explain things better or post some code examples.
    Hope this helps,
    CowKing

  • Invoking JSF actions from a hyperlink

    I suspect I already know the answer to this question based on my experiments and what I've read on the web and in books, but I thought I'd ask here just in case.
    The basic problem is that I would like to invoke JSF from a hyperlink. For example: mystore.com/displayProduct.faces?id=1234
    But I can't. JSF just seems to be (intentionally) built not to allow access to the JSF lifecycle via GET requests. Which makes it fine for web sites that are composed simply of loads of forms, but seems quite unsuitable for web sites that need to display products and search results via links that are easy to bookmark and easy for search engines to crawl.
    Thanks for any words of wisdom anyone might have...

    Thanks for the reply and the link. I had a look at the linked thread and might be able to use that technique for getting parameters out of a GET request into my action, but I still need to get JSF to call my action method somehow and there is no way that I can see to tell it which method to call.
    Also, it seems like manually reading values from the request is sidestepping a lot of JSF and losing out on the value that it adds, i.e. validating and converting the parameters for me. I could manually populate components in the bean and then call the validators and converters myself, but still.

  • Jsf validation

    Hi ,
    I have got a problem here.Please help me solve this.
    So its like this:
    I have one jsp(jsf)page , it has many validators .and some validation i did manually in action method.
    So the problem comes when validating when i clicked the save button first all the page level validation are validated and after giving correct value and saving again the validation message i gave are coming . So how can i get all message at a time.
    Thanks

    You can try this quick-and-dirty example:
    <h:messages globalOnly="true">
       <h:message for="tag1" />
       <f:verbatim><br/></f:verbatim>
       <h:message for="tag2" />
       ... // add other messages here
    </h:messages>Where tag1 and tag2 are id/name of your JSF tags on your form. However, I'm new to JSF so this may not be a best solution for you. You could give it a try and see how you go -:)

Maybe you are looking for