JSF Actions and Views

Now that we’ve set up our managed beans, we can start looking at the JSF pages themselves. Let’s start with the home page for the Library application, which is shown in Example 5-3.

Example 5-3. index.jsp

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
 
<html>
 
 <f:view>
 <head>
    <title>JSF Library Home Page</title>
    <link rel="stylesheet" type="text/css" href='<%=
                            request.getContextPath() + "/css/app.css" %>'>
 </head>
 <body>
    <h:form>
    <h1>JSF Library</h1>
    <hr>
    Welcome to the JSF library.
    <p>
    <h:outputText
        value="You are logged in as  #{usersession.currentUser.username}"/>
    <p>
    <h:commandButton action="viewbooks"  value="View Books"/>
    <h:commandButton action="addbook"
       rendered="#{usersession.currentUser.librarian}" value="Add Book"/>
 
    <hr>
    <h:commandLink rendered="#{not usersession.loggedIn}" action="login">
        <h:outputText value="Log In"/>
    </h:commandLink>
    <h:commandLink rendered="#{usersession.loggedIn}"
        action="#{usersession.logout}">
        <h:outputText value="Log Out"/>
    </h:commandLink>
 
    </h:form>
 </body>
</f:view>
<html>

This file lives in the root directory of our web application. But if we try and access it at http://server/library/index.jsp, we’ll get a messy error. Instead, we access it via the FacesServlet, which is responsible for managing the JSF lifecycle. Earlier, we set up a mapping in web.xml that forwards all requests with a .faces extension to the FacesServlet. The FacesServlet sets up a ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.