Showing posts with label Request. Show all posts
Showing posts with label Request. Show all posts

Tuesday, August 6, 2013

Converters In Java Server Faces--How to convert form data into respective data types?

Converters in JSF :-


In a web application the data entered in a form is always of String data type.
Consider a web page form having first name,last name and Age.Here names are of String type and Age is Number data type. But when the data is sent from form to server every filed is String type.

How to convert Age field data to integer type before assigning it to managed bean/backing bean? We can explicitly convert it by using Integer.parseInt() etc.Doing this way is tedious and not reusable.

Does JSF provide any mechanism to handle this?
Yes JSF provides a mechanism to convert these String types into respective data type.

  • For implicit data types JSF provides implicit conversion
  • For non primitive types we need to convert explicitly by using Standard Converters( for converting String to Date etc.)or by creating custom converters

First we will see different standard converters.


    SNO
    NAME
    MAIL
    1
    ByteConverter
    Converts input String value to java.lang.Byte
    2
    BooleanConverter
    Converts input String value to java.lang.Boolean
    3
    BigDecimalConverter
    Converts input String value Java.lang.BigDecimal
    4
    BigIntegerConveter
    Converts input String value to java.lang.BigInteger
    5
    CharacterConverter
    Converts input String value to java.lang.Character
    6
    DateTimeConverter
    Converts input String value to java.util.Date
    7
    NumberConverter
    Converts input String value to java.lang.Number
    8
    IntegerConverter
    Converts input String value to java.lang.Integer
    9
    FloatConverter
    Converts input String value to java.lang.Float

Similarly we have EnumConverter,ShortConverter etc.

There are three different ways to use this Standard converters.
  1. Using Converter attribute in input tags
  2. Using nested sub-tag <f:converter>
  3. Using standard converters like <f:convertDateTime>,<f:convertNumber> etc.
Lets see each of the above with examples.

1.Using Converter attribute in input tags :-
  • inputText,inputSecret,inputHidden,outputText are supported tags
  • Lets takes an example of entering date and using converter attribute
    <%@ 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>Date</title>
</head>
<body>
<f:view>
<h:form>
Date <h:inputText id="myDate" value="#{loginBean.date}"
converter="javax.faces.DateTime">
</h:inputText>
<h:commandButton value="submit" ></h:commandButton>
<h:message for="myDate"></h:message>
</h:form>
</f:view>
</body>
</html>
  • Here we have used DateTime converter attribute in input text,the value entered should be like Aug 5, 2013--> mmm d, yyyy. If we enter a value with different value it will throw error it is displayed by using <h:message> tag



2.Using nested sub-tag <f:converter> :-

<h:inputText id="myDate" value="#{loginBean.date}">
<f:converter converterId="javax.faces.DateTime" />
</h:inputText>

Here we have used converter tag inside inputText tag

3.Using standard converters :-

we will use <f:convertdateTime> tag
<h:inputText id="myDate" value="#{loginBean.date}">
<f:convertDateTime type="date" dateStyle="short" />
</h:inputText>

There are different types of dateStyles like short,full etc.
Short type will expect date as mm/dd/yyyy or mm/dd/yy .
Long type will expect date as August 5, 2013 etc, this is generally used for outputText tag.

We can change/add the behavior of this converters by developing custom converters.
This will be discussed in my next post.



Happy Learning

Please provide your valuable comments on this article and share it across your network.



Thursday, July 4, 2013

Introduction to Entity beans in Java Persistence API (JPA)

Hi All,

In this post we will discuss about Java Persistence API(JPA) entity bean.

Lets have a brief introduction about JPA.
JPA is a Java data base framework which eases interaction with database by providing following features
  1. Java Persistence Query language (JPQL)
  2. Object relational mapping
  3. Providing annotation etc.
The most important aspect in JPA is a Java bean class .
Bean in Java is a simple class with properties and their getter and setter methods

In JPA we call this bean with a special name called as Entity.

Entity Bean :- is an exact replica of a table in a database,it is independent of database used.
  • The mapping between a Entity Bean and data base table is configured in persistence.xml file
  • There are different types of annotations(@) which helps in representing primary keys,table name etc.
  • Annotation are in simple metadata(Data about Data),they give extra information to compiler
  • A normal Java bean can be converted into a Entity by using @Entity annotation
we will discuss more about annotations in upcoming posts.

In this post we will see how to write a Entity Bean

Environment used :-
  • Eclipse Juno
  • Oracle
  • JPA 2.0 jars
Lets have below COMPANY table in data base

    SNO
  • NAME
    MAIL
    1
  • Google
  • google@gmail.com
    2
  • Yahoo
  • yahoo@yahoo.com
    3
  • Microsoft
  • microsoft@live.com

Now we will write a Entity class for the same. In Eclipse its simple to create most of the required code will be auto generated.
  1. Switch to JPA perspective in Eclipse
  2. Configure data base connection by using Data Source Explorer view(window-->Show view-->Data Source Explorer)
  3. Create a JPA project(File—New-->Create JPA project)
  4. Open the project,in JPA content you will find persistence.xml file
  5. Now select the project click on new-->others--JPA Entity from tables
  6. Select the data base connection , schema configured in step 2 and select tables that you want to generate Entities
  7. Click the check box-- update in persistence.xml
  8. Select a primary key generator type like Auto etc(Not mandatory) continue and click finish
Lets see the code that gets generated for COMPANY table


@Entity
public class Company implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private BigDecimal sno;
private String mail;
private String name;
public Company() {
}

public String getMail() {
return this.mail;
}

public void setMail(String mail) {
this.mail = mail;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public BigDecimal getSno() {
return this.sno;
}

public void setSno(BigDecimal sno) {
this.sno = sno;
}

}


Explanation :-

Here we need to take a look at two annotations

  1. @Entity :- Gives a identification for a normal Java bean as entity
  2. @Id :- Indicates the primary key in the table

Here we have three properties and their getter and setter methods,we will be accessing (setting/retrieving )the properties by using these methods.

There are lot more annotations available for various purposes will explain in details in my upcoming posts.

Now have a look at persistence.xml, we will find the Entity class added.

                         Happy Learning

Please provide your valuable comments on this article and share it across your network.


Sunday, June 30, 2013

Widening VS Auto Boxing during Overloading

Hi,

In this post we will see the usage of Over loading ,Boxing and widening concepts with an example.

Lets see how the above concepts are related with an example :

Example :-
public class WideningBoxing {
//Overloading example with boxing and widening
public void method(Integer x, Integer y)
{
System.out.println(" in Integer ");
}

public void method(float x, float y)
{
System.out.println("in float");
}
public static void main(String[] args) {
WideningBoxing wb=new WideningBoxing();
wb.method(1, 2);
}
}


Explanation :- Here we have two methods with same names,different parameter types.
We are calling this method from main .

Now the question is which method will be invoked when we call wb.method(1, 2);

The method with Integer or method with float parameters?


JVM will prefer to take widening than boxing here.
So the output will be
in float

The main reason behind this is widening was being implemented before auto boxing, so the API writers thought that the existing functionality should work same ,it should not be changed by adding new auto boxing feature.


This is the common Java interview Question


Note :- Widening is preferred than Boxing 

This is the key take away point from this post.

                     Happy Learning

Please provide your valuable comments on this article and share it across your network.




Friday, June 21, 2013

Implementing Remember me functionality using Cookies in Java

Hi All,
Welcome to Java-recent.
In this post we will discuss about implementing Remember Me feature in Java web applications.
We would have come across sites where we will have a login form with an option like remember me etc.When we enter credentials and click on this option ,later point return to this page previously  entered credentials will be shown.How did this implementation happen?

One way of implementing this is using Cookies.

Cookie:- is a information sent from server to a browser and gets stored in browsers folder,generally used to maintain state of an user.This data will be sent back to server for subsequent requests

"A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website. When the user browses the same website in the future, the data stored in the cookie is sent back to the website by the browser to notify the website of the user's previous activity." reference from http://en.wikipedia.org/wiki/HTTP_cookie

Cookies are usually transferred in header data

Here we will implement rembember me using functionality using
  • Cookies
  • JSF 2.0
  • Eclipse IDE

Scenario :-
  • We will have a login page with following components
    • UserName text field
    • Password secret input field
    • Submit button
    • Remember me check box
  • A managedbean which will bind these components and perform validations and setting cookies etc.

Source code :-

RememberMe.jsp
<%@ 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>Remember me</title>
</head>
<body>
<f:view>
<h:form>
User name<h:inputText value="#{rememberBean.uName }"></h:inputText>
<br>
Password <h:inputSecret value="#{rememberBean.password }"></h:inputSecret>
<br>
<h:commandButton value="Submit" action="#{rememberBean.submit }"></h:commandButton>
<h:selectBooleanCheckbox value="#{rememberBean.checkBox }"></h:selectBooleanCheckbox>Remember me
</h:form>
</f:view>
</body>
</html>

RememberBean.java
@RequestScoped
public class RememberBean {
private String uName;
private String password;
private boolean checkBox=false;
private String virtualCheck;

public RememberBean()
{
isChecked();
}
public String getVirtualCheck() {
return virtualCheck;
}

public void setVirtualCheck(String virtualCheck) {
this.virtualCheck = virtualCheck;
}

public String getuName() {
return uName;
}

public void setuName(String uName) {
this.uName = uName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public boolean isCheckBox() {
return checkBox;
}

public void setCheckBox(boolean checkBox) {
this.checkBox = checkBox;
}

public String submit() {
if (uName != null && password != null) {
FacesContext fc=FacesContext.getCurrentInstance();
if (checkBox == true) {
virtualCheck="true";
//getting current instance of faces context
Cookie cUserName = new Cookie("cUserName", uName);
Cookie cPassword = new Cookie("cPassword", password);
Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
cUserName.setMaxAge(120);
cPassword.setMaxAge(120);
cVirtualCheck.setMaxAge(120);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cUserName);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cPassword);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);
}
else
{
virtualCheck="false";
Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);
}
}
return "always";
}
public void isChecked()
{
FacesContext fc=FacesContext.getCurrentInstance();
Cookie cookiesArr[]=((HttpServletRequest)(fc.getExternalContext().getRequest())).getCookies();
if(cookiesArr!=null&&cookiesArr.length>0)
for (int i = 0; i < cookiesArr.length; i++) {
String cName=cookiesArr[i].getName();
String cValue=cookiesArr[i].getValue();
System.out.println("---cValue----"+cValue);
if(cName.equals("cUserName"))
{
setuName(cValue);
}else if(cName.equals("cPassword"))
{
setPassword(cValue);
}else if(cName.equals("cVirtualCheck"))
{setVirtualCheck(cValue);
if(getVirtualCheck().equals("false"))
{
setCheckBox(false);
setuName(null);
setPassword(null);
}
else if(getVirtualCheck().equals("true"))
{System.out.println("here in line110");
setCheckBox(true);
}
}
}
{
}
}
}

Explanantion :-
  • submit() method is linked to submit button in RememberMe.jsp
    Here in this method we set the cookies for username,password and check box,if remember me check box is clicked
    Cookie cUserName = new Cookie("cUserName", uName);
    Cookie cPassword = new Cookie("cPassword", password);
    Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
Here we are creating Cookie objects

Below setting age of a cookie in seconds
    cUserName.setMaxAge(24*60*60);
    cPassword.setMaxAge(24*60*60);
    cVirtualCheck.setMaxAge(24*60*60);

Below adding cookies to response
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cUserName);
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cPassword);
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);

Then in the bean constructor we are invoking a method called isChecked()

This method will check if already exact cookie is there.If cookies are there then we will retrive their values based on their names and assign it respective fields.
Cookie cookiesArr[]=((HttpServletRequest)(fc.getExternalContext().getRequest())).getCookies();
if(cookiesArr!=null&&cookiesArr.length>0)
for (int i = 0; i < cookiesArr.length; i++) {
String cName=cookiesArr[i].getName();
String cValue=cookiesArr[i].getValue();
System.out.println("---cValue----"+cValue);
if(cName.equals("cUserName"))
{
setuName(cValue);
}else if(cName.equals("cPassword"))
{
setPassword(cValue);
}else if(cName.equals("cVirtualCheck"))
{setVirtualCheck(cValue);
if(getVirtualCheck().equals("false"))
{
setCheckBox(false);
setuName(null);
setPassword(null);
}
else if(getVirtualCheck().equals("true"))
{System.out.println("here in line110");
setCheckBox(true);
}

Ouptput :-

with out checking remember me check box


With checking remember me check box


Note :- in order to save password browser will ask/prompt user to save password or not
Irrespective of Java web technologies and browsers setting and retrieving cookies will play a major role
In eclipse web.xml and faces-config.xml will be automatically created
If we want to delete a cookie,the simplest method is to set its maximum age to zero seconds

Some of the popular posts are :-



Happy Learning

Please provide your valuable comments on this article and share it across your network.



Like and Share