JSF: JavaServer Faces

  • View
    26

  • Download
    2

Embed Size (px)

DESCRIPTION

JSF: JavaServer Faces. Vinay Kumar. Session Schedule. JSF Introduction Page Navigation Managed Beans Expression Language Properties File. Session Schedule -contd. Event Handling HTML Library Validation JDBC in JSF Data Tables. Session Schedule -contd. Ajax-4-JSF - PowerPoint PPT Presentation

Text of JSF: JavaServer Faces

  • Vinay Kumar

  • JSF IntroductionPage NavigationManaged BeansExpression LanguageProperties File

  • Event HandlingHTML LibraryValidationJDBC in JSFData Tables

  • Ajax-4-JSFBasic component tagsAdvanced custom tagsCustom components

  • Different views of JSFComparing JSF to standard servlet/JSP technologyComparing JSF to Apache Struts

  • A set of Web-based GUI controls and associated handlers? JSF provides many prebuilt HTML-oriented GUI controls, along with code to handle their events.

    A device-independent GUI control framework? JSF can be used to generate graphics in formats other than HTML, using protocols other than HTTP.

    A better Struts? Like Apache Struts, JSF can be viewed as an MVC framework forbuilding HTML forms, validating their values, invoking businesslogic, and displaying results.

  • Custom GUI controls JSF provides a set of APIs and associated custom tags to create HTML forms that have complex interfaces Event handling JSF makes it easy to designate Java code that is invoked when forms are submitted. The code can respond to particular buttons, changes in particular values, certain user selections, and so on. Managed beans In JSP, you can use property="*" with jsp:setProperty to automatically populate a bean based on request parameters. JSF extends this capability and adds in several utilities, all of which serve to greatly simplify request param processing. Expression Language JSF provides a concise and powerful language for accessing bean properties and collection elements

  • Bigger learning curve To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet APIs. To use MVC with JSF, you have to be comfortable with the standard JSP and servlet APIs and a large and elaborate framework that is almost equal in size to the core system. This drawback is especially significant with smaller projects, near-term deadlines, and less experienced developers; you could spend as much time learning JSF as building your actual system.

    Worse documentation Compared to the standard servlet and JSP APIs, JSF has fewer online resources, and many first-time users find the online JSF documentation confusing and poorly organized. MyFaces is particularly bad.

  • Static Navigation

  • When form submitted A static page is displayed Static result No business logic, beans, or Java code of any sort The return path is specified in the button itself. Main points Format of original form Use of navigation-rule in faces-config.xml

  • Input form has following format:

    HTML markup

    HTML markup and h:blah tags

    HTML markup

    faces-config.xml specifies navigation rules:

    /blah.jsp

    some string/WEB-INF/results/something.jsp

  • The h:form element ACTION is automatically self (current URL) METHOD is automatically POST Elements inside h:form Use special tags to represent input elements h:inputText corresponds to h:inputSecret corresponds to h:commandButton corresponds to In later sections, we will see that input elements will be associatedwith bean properties For static navigation, specify simple string as action of h:commandButton

    String must match navigation rule from faces-config.xml

  • register.jsp

    New Account Registration

    Email address: Password:

  • Result resigter.jsp

  • General format

    Specifying the navigation rules

    /register.jsp

    register/WEB-INF/results/result.jsp

  • RequestDispatcher.forward used So page can/should be in WEB-INF Example code: /WEB-INF/results/result.jsp

    Success

    You have registered successfully.

  • Note that the URL is unchanged

  • Filename/URL correspondence Actual files are of the form blah.jsp URLs used are of the form blah.faces You must prevent clients from directly accessing JSPpages Since they would give erroneous results Strategies You cannot put input-form JSP pages in WEB-INF Because URL must correspond directly to file location So, use filter in web.xml. But: You have to know the extension (.faces) Assumes no non-JSF .jsp pages This is a major drawback to JSF design

  • FacesRedirectFilter

    public class FacesRedirectFilter implements Filter {private final static String EXTENSION = "faces";public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)throws ServletException, IOException {HttpServletRequest request = (HttpServletRequest)req;HttpServletResponse response = (HttpServletResponse)res;String uri = request.getRequestURI();if (uri.endsWith(".jsp")) {int length = uri.length();String newAddress =uri.substring(0, length-3) + EXTENSION;response.sendRedirect(newAddress);} else { // Address ended in "/"response.sendRedirect("index.faces");}}

  • faces-redirect-filter

    coreservlets.FacesRedirectFilter

    faces-redirect-filter*.jsp

  • Dynamic Navigation

  • A form is displayed Form uses f:view and h:form The form is submitted to itself Original URL and ACTION URL are http:///blah.faces A bean is instantiated Listed in the managed-bean section of faces-config.xml The action controller method is invoked Listed in the action attribute of h:commandButton The action method returns a condition A string that matches from-outcome in the navigation rules in faces-config.xml A results page is displayed The page is specified by to-view-id in the navigation rules in faces-config.xml

  • 1) Create a beanA) Properties for form dataB) Action controller methodC) Placeholders for results data2) Create an input formA) Input fields refer to bean propertiesB) Button specifies action controller method that will return condition3) Edit faces-config.xmlA) Declare the beanB) Specify navigation rules4) Create results pages Output form data and results data with h:outputText5) Prevent direct access to JSP pages Use a filter that redirects blah.jsp to blah.faces

  • Collects info to see if user qualifies for health plan When form submitted, one of two possibleresults will be displayed User is accepted into health plan User is rejected from health plan Main points Specifying an action controller in the form Creating an action controller method in the bean Using faces-config.xml to Declare bean Map return conditions to output pages

  • Specify the controller with #{beanName.methodName}

    Controller method returns strings corresponding to conditions If null is returned, the form is redisplayed Unlike with Struts, the controller need not extend a special class Use faces-config.xml to declare the controller as follows

    controller namecontroller classrequest

    Add multiple navigation-rule entries to faces-config.xml One for each possible string returned by the controller If no string matches, the form is redisplayed

  • (A) Properties for form data Postponed until next session(B) Action controller methodpublic class HealthPlanController {public String signup() {if (Math.random() < 0.2) {return("accepted");} else {return("rejected");}}}(C) Placeholders for results data Postponed until next session

  • Same general syntax as in previous example Except for action of commandButton

    First name: Last name: ...

  • (A) Declaring the bean

    healthPlanController

    coreservlets.HealthPlanController

    request

  • (B) Specifying navigation rules Outcomes should match return values of controller

    (bean definitionsfrom previous page)

    /signup.jsp

    accepted/WEB-INF/results/accepted.jsp

    rejected/WEB-INF/results/rejected.jsp

  • /WEB-INF/results/accepted.jsp

    Accepted!

    You are accepted into our health plan.Congratulations.

  • /WEB-INF/results/accepted.jsp

    Accepted!

    You are accepted into our health plan.Congratulations.

  • /WEB-INF/results/rejected.jsp

    Rejected!

    You are rejected from our health plan.Get lost.

  • Use filter that captures url-pattern *.jsp No changes from previous example

  • Wildcards in navigation rule * for from-view-id matches any starting page

    *

    success/WEB-INF/results/success.jsp

    Getting the request and response objectsHttpServletRequest request =(HttpServletRequest)context.getRequest();HttpServletResponse response =(HttpServletResponse)context.getResponse(); In some environments, you cast results of getRequest and getResponse to values other than HttpServletRequest and HttpServletResponseE.g., in a portlet environment, you might cast result toPortletRequest and PortletResponse

  • If you have several different addresses inyour app, it is OK to alternate

    Stuff for bean1

    Rules for address that uses bean1

    Stuff for bean2

    Rules for address that uses bean2

    Of course, it is also OK to put all bean defs at the top,followed by all navigation rules.

  • Using beans to represent requestparameters Declaring beans in faces-config.xml Referring to beans in input forms Outputting bean properties

  • 1) Create a beanA) Properties for form dataB) Action controller methodC) Placeholders for results data2) Create an input formA) Input fields refer to bean propertiesB) Button specifies action controller method that will return condition3) Edit faces-config.xmlA) Declare the beanB) Specify navigation rules4) Create results pages Output form data and results data with h:outputText5) Prevent direct access to JSP pages Use a filter that redirects blah.jsp to blah.faces

  • When form submitted, three possible results Error message re illegal email address Error message re illegal password Success New features Action controller obtains request data from within bean Output pages access bean propert