About Me

My photo
Ernakulam, Kerala, India
I am Sajadh, author of this blog. I run this with loads of passion.
If you are into java, you may find lot of interesting things around ...
Advance thanks for your queries to sajadhaja90@gmail.com.

Thursday, 14 February 2013

JSF 1.x Sample Application -1 [Validation, Resource bundles and Navigation ]

                                                                                                                   NEXT EXAMPLE

1. Create JSF Project

Create a new Dynamic Web Project "de.vogella.jsf.starter".

2. Domain model

Create a new package de.vogella.jsf.starter.model and the following class.

package de.vogella.jsf.starter.model;

public class User {
  private String name;
  private String password;
  
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  
  public String login(){
    // Image here a database access to validate the users
    if (name.equalsIgnoreCase("tester") && password.equalsIgnoreCase("tester")){
      return "success";
    } else {
      return "failed";
    }
    
  }
  
} 
 

Tip

Please note that we are hard-coding that only user tester with password tester can login.

Create the following class.

package de.vogella.jsf.starter.model;

import java.util.Random;

public class Card {
  private int left;
  private int right;
  private int result = 0; 

  public Card() {
    Random random = new Random();
    int i = 0;
    int j = 0;
    do {
      i = random.nextInt(10);
    } while (i <= 4);

    do {
      j = random.nextInt(100);
    } while (j <= 20);

    left = i;
    right = j;
  }

  public int getLeft() {
    return left;
  }

  public void setLeft(int left) {
    this.left = left;
  }

  public int getRight() {
    return right;
  }

  public void setRight(int right) {
    this.right = right;
  }

  // Controller

  public String show() {
    result = left * right; 
    return "success";
  }
  
  public String clear() {
    result = 0; 
    return "clear";
  }

  public int getResult() {
    return result;
  }

  public void setResult(int result) {
    this.result = result;
  }

} 


Tip

The class Card contains currently some controller code. The next chapter will demonstrate how to keep your model code clean and how to use controllers directly.

3. Register your managed beans

Double-click on faces-config.xml and select the tab "ManagedBeans". Register your User.java and Card.java as managed beans.

4. Validators

JSP allows to define validators which allows to check certain values which are placed in the UI. Create therefore the following class.

package de.vogella.jsf.starter.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class LoginValidator implements Validator {
  public void validate(FacesContext context, UIComponent component,
      Object value) throws ValidatorException {
    String user = (String) value;
    if (!user.equalsIgnoreCase("tester")) {
      FacesMessage message = new FacesMessage();
      message.setDetail("User " + user + " does not exists");
      message.setSummary("Login Incorrect");
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
    }
  }
} 

Select your faces-config.xml and select the tab Component. Select Validators and press Add.



5. Resource bundle for messages

With JSP it is easy to use resource bundles for the static text in your JSP application. Create the following file "messages.properties" in your source folder under the package "de.vogella.jsf.starter".

user=User
password=Password
login=Login
hello=Moin
left=Left Side
right=Right Side
result=  Result
show= Show Result
next= New Test
reset= Reset 

6. JavaServer Page with JSF components

Create a new JSP page "LoginView.jsp" and change the code to the following:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<f:view>
  <f:loadBundle basename="de.vogella.jsf.starter.messages" var="msg" />
  <h:form>
    <h:panelGrid columns="2">
      <h:outputLabel value="#{msg.user}"></h:outputLabel>
      <h:inputText value="#{user.name}">
      <f:validator
          validatorId="de.vogella.jsf.starter.validator.LoginValidator" />
      </h:inputText>
      <h:outputLabel value="#{msg.password}"></h:outputLabel>
      <h:inputSecret value="#{user.password}">
      </h:inputSecret>
    </h:panelGrid>
    <h:commandButton action="#{user.login}" value="#{msg.login}"></h:commandButton>
    <h:messages layout="table"></h:messages>
  </h:form>
</f:view>
</body>
</html> 

Lets explain a few fields.


Table 1. 
Element Description
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> Makes the core and html tags available in the page
<f:view> Indicates that the following will use JSF components.
<f:loadBundle basename="de.vogella.jsf.starter.messages" var="msg"/> load the resource / message bundle which is then available in the application under the name msg
<h:form> Starts a form
<h:outputLabel value="#{msg.user}"></h:outputLabel> Define a label which used the text user define in the resource bundle
<h:inputText tabindex="1" value="#{user.name}"></h:inputText> Define a input field which used the managed bean user and maps to field name
<h:inputSecret tabindex="2" value="#{user.password}"> Masked input files, mapped to the managed bean user and field password
<h:commandButton action="#{user.login}" value="#{msg.login}"></h:commandButton> The button is mapped to the method user.login


Create another JSP "Trainer.jsp" with the following code.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
  <f:loadBundle basename="de.vogella.jsf.starter.messages" var="msg" />
  <h:form>
    <h:panelGrid columns="3">
      <h:outputLabel value="#{msg.left}"></h:outputLabel>
      <h:inputText id="left" value="#{card.left}"></h:inputText>
      <h:message for="left"></h:message>

      <h:outputLabel value="#{msg.right}"></h:outputLabel>
      <h:inputText id="right" value="#{card.right}">
      </h:inputText>
      <h:message for="right"></h:message>

    </h:panelGrid>
    <h:commandButton action="#{card.show}" value="#{msg.show}"></h:commandButton>
    <h:commandButton action="#{card.clear}" value="#{msg.reset}"
      immediate="true"></h:commandButton>
    <h:messages layout="table"></h:messages>
  </h:form>

  <h:panelGrid rendered="#{card.result!=0}" columns="3">
    <h:outputLabel value="#{msg.result}"></h:outputLabel>
    <h:inputText id="result" value="#{card.result}">
    </h:inputText>
    <h:message for="result"></h:message>
  </h:panelGrid>


</f:view>
</body>
</html> 

Create another JSP FailedLogin.jsp with the following code.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
  <h1>Failed Login.</h1>
</f:view>
</body>
</html> 

7. Navigation Rule

Select your faces-config.xml and select the tab "Navigation Rule". Make the palette available if necessary.


Select Page and click in the workarea. Add LoginView and Trainer to the workspace.


Click on Link, then on LoginView and then on Trainer. You should have now an arrow which indicates a navigation rule.


Click in the Palette on Select. Select then the arrow and the properities view. Input "success" in the From – Outcome



Tip

The user bean return the String success. In the navigation rule you now defined that if we receive "success" then we should be going to the next page.



Add a navigation rule so that in the case the user does not use the right user / password you send him to the failure page.

8. Run your webapplication

To run your webapplication, select LoginView.jsp, right mouse-click- >run as -> run on server.

Tip

Remember that we are hard-coding that only user "tester" with password "tester" can login. Try another user this should not work.

You should be able to login with the right user and move to the next page.



                                                                      NEXT EXAMPLE

1 comment:

  1. Good explanation on Java programming..Thanks for sharing..

    best dissertation services

    ReplyDelete

You can enter queries here...