Pages

Friday, February 11, 2011

JSF(Java Server Faces) tutorial sample application

Java Server Faces(JSF) is a specification which defines a Component based MVC framework.
Typically,
Model       - Managed Beans
View         - Components
Controller  - FacesServlet
Building high quality web application user interfaces is hard as it involves HTTP request/response model,browser capabilities,need to support multiple client device types.
JSF to the rescue:
a)Uses components,not actions,more like Swing,less like Struts.
b)Huge vendor and industry support.
c)JSP,Servlets,Struts uses no built-in component model.
d)A JSP application cannot manage UI elements as stateful objects on the server,as JSF app can.
e)Extensible Architecture (Easy to use third party components)
 etc.
Main Components of JSF:
1)An API for representing UI components and managing their state.(like Handling events,server side validation,page navigation,etc.)
2)Two JSP custom tag libraries for expressing UI components with-in a JSP page and for writing components to server side objects.
A simple example :
Directory Structure (in NetBeans)



1) Create a JSP page : mylogin.jsp (View) - it includes JSF components as well
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello Friend!</h1>

        <f:view>
            <h:form>
                <h:panelGrid>
                    Username:
                    <h:inputText id="uname" value="#{user.uname}"></h:inputText>

                    Password:
                    <h:inputSecret id="pwd" value="#{user.pwd}"></h:inputSecret>
                </h:panelGrid>
                <h:commandButton id="submit" type="submit" value="Login" action="#{user.validateUser}"></h:commandButton>

            </h:form>
        </f:view>

    </body>
</html>

Now create a Success page (success.jsp - shows Hello) and failure page (failure.jsp - shows invalid credentials)
After that create a POJO (usually called a backing bean) - contains setters and getters and validation code.
UserBean.java
package com.praveen.first.jsfapp;

/**
 *
 * @author S L N V Praveen
 */
public class UserBean {

    private String uname;
    private String pwd;

    public UserBean(){ }

    public void setUname(String uname)
    {
        this.uname = uname;
    }
    public String getUname()
    {
        return uname;
    }

    public void setPwd(String pwd)
    {
        this.pwd = pwd;
    }
    public String getPwd()
    {
        return pwd;
    }

    public String validateUser()
    {
        if(getUname().equals("praveen") && getPwd().equals("praveen"))
            return "success";
        else
            return "failure";
    }

}
Now create faces-config.xml (like struts-config.xml)
<faces-config version="1.2" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
    <managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>com.praveen.first.jsfapp.UserBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/mylogin.jsp</from-view-id>
        <navigation-case>
            <from-action>#{user.validateUser}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/success.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{user.validateUser}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/failure.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>

</faces-config>
And create web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>com.sun.faces.verifyObjects</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.validateXml</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/faces-config.xml</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/mylogin.jsp</welcome-file>
    </welcome-file-list>
</web-app>
Now run the project.(used GlassFish 3.1)
Note : Before running the project on the server make sure the port 8080 is not used by any other service.If it's in use then the server start to fail saying "Port occupied : 8080"

Happy Coding...!!!

No comments:

Post a Comment