Showing posts with label Cookie. Show all posts
Showing posts with label Cookie. Show all posts

Sunday, November 17, 2013

Page Refreshing

Hi,

In this post we will discuss about refreshing a web page at regular interval of time.
There are many ways to do this .
  • Using Java script
  • Setting response headers etc.

We would have seen many popular websites like Facebook, GMail etc. where a page will be refreshing automatically and updating the content at regular intervals of time.
Lets see how to refresh a JSP page with an example.

By using response header
Example :-

PageRefresh.jsp
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@page import="java.util.Date" %>
<head>
<title>Page refresh</title>
</head>
<body>
<%response.setHeader("refresh","5");%>
<%Date date=new Date(); %>
<%="Current time " +date %>
</body>
</html>

Here we have used response.setHeader("refresh","5") ,which takes two parameters—refresh attribute and time interval for page refreshing in seconds. PageRefresh.jsp will be refreshing every 5 seconds and displaying the cureent date and time

Output:-

Current time Sun Jun 30 10:21:21 IST 2013

Current time Sun Jun 30 10:21:26 IST 2013

Environment details :-
  • Eclipse Juno
  • Apache Tomcat

                      Happy Learning

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



Sunday, August 4, 2013

Passing values to methods in Java-Primitives and Objects

In this post we will discuss about how method calling ,value passing happens in Java.

1.Passing Object reference variables to a method :-
  • when we pass an object to a method we are not actually passing object itself, we are passing object reference
  • Reference variable holds the address location of object and a way to load into memory
  • We are not passing actual reference variable,but a copy of reference variable-which holds the copy of bits present in actual value

Lets see below code snippent

Employee emp1=new Employee();
method1(emp1);
void method1(Employee emp)
{
}
Here both emp1 and emp point to same Employee Object in heap.

Example1 :-

public class ObjectReference {
private int var1;
private int var2;

public ObjectReference(int x, int y) {
var1 = x;
var2 = y;
}

public static void main(String[] args) {
ObjectReference op = new ObjectReference(5, 10);
System.out.println("before modify " + op.var1 + "&&" + op.var2);
op.modify(op);
System.out.println("after modify " + op.var1 + "&&" + op.var2);
}

void modify(ObjectReference pop) {
pop.var1 = pop.var1 + 10;
pop.var2 = pop.var2 + 10;
System.out.println("in modify " + pop.var1 + "&&" + pop.var2);
}
}



Output :-
before modify 5&&10
in modify 15&&20
after modify 15&&20

Here both op and pop reference variables are referring to same ObjectReference object .If one reference variable tries to change the value autotically it gets reflected to another varaible.

In the above example in change method we changed the value of var1 and var2 and when we print the value in main method it got reflected.
Now lets see what happens in case of primitive data types.

2.Passing primitive variables to a method :-
When we are passing primitive values to a method we are actually passing copy of bits that represent a value.Suppose we have int a=5,when we pass a to a method we are actually passing copy of bits of value 5. For this we use a terminology passbyvalue rather its passbycopyofvalue .

Example :-
public class PrimitivePass {
int a = 10;

public static void main(String[] args) {
PrimitivePass pp = new PrimitivePass();
System.out.println("Before change" + pp.a);
pp.change(pp.a);
System.out.println("After change" + pp.a);
}

void change(int pNum) {
pNum = pNum + 10;
System.out.println("in change" + pNum);
}
}

output :-
Before change10
in change20
After change10

From the output we can observe that value of a is not changed ,but in previous case we observed for object references the value has changed.

Note :-
  • While passing an Object we actually pass copy of the object reference
  • While passing a primitive type we pass the bits value stored in that variable
  • In both the cases we send copy of bits,in primitives actual value is stored but in case of Object reference it stores the address of the object

Happy Learning

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



Saturday, July 27, 2013

Basic Annotations in Java Persistence API(JPA)

Hi,

Today we will discuss some of the basic JPA annotations.

Annotations :-
  • @Table
  • @Column
  • @Temporal
  • @Transient

Lets consider below table -Company

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

1.@Table :-is used to map your entity java bean with the table
In general your table name and entity bean will have same name at that time there is no need to use @Table
If the Entity bean is different from the table name we map it by using @Table annotation

Example :-
Lets take the above table-Company ,but my entity bean name is named as Organization  then we can use @Table to map them

@Entity
@Table(name="Company")
Public class Organization{.......}


2.@Column :- is used to map an instance variable with a column in a table
If the variable name and database column name is same ,then there is no need to use column
This is similar to @Table

Example :-
Lets take the data base column -Name in the above table
In Entity bean we have companyName.so how to map them?

@Column(name="Name")
Private String companyName;

3.@Temporal :-
  • In Java we have java.util.Date and java.util.Calendar classes,if we wnat to persist them into data base we should use @Temporal
  • Temporal are set of time based types
Example :-
@Temporal(TemporalType.DATE)
Date currentDate;

In Entity                                                                   Mapped to data base
  • TemporalType.DATE
  • Mapped to java.sql.Date
  • TemporalType.TIME
  • Mapped to java.sql.Time
  • TemporalType.TIMESTAMP
  • Mapped to java.sql.Timestamp

4.@Transient :-
  • Attributes that are part of Entity but should not be persisted should be marked as @Transient
  • Suppose we have a attribute lastName and should not be persisted to data base,we use@Transient
Example :-
@Transient
private String lastName;

There are many annotations in JPA,each one of them has special functionality which i will discuss in my later posts


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