Tuesday, 14 May 2013

Java some common type conversions

We often come across situations where data needs to be converted from one type to other and back again..or some other consecutive conversions.

However it is quite easy in case of java. This article will  be helpful for the beginners.

Conversions:

int to String  -  just add an extra empty string

int i = 5;
String str = "" + i ;


String to int   -  use the function parseInt( )

String str = "123" ;
int i = Integer.parseInt( str ) ;

char to String  -  just add an empty string

char c = 'b';
String str = "" + c ;

String to char - use function charAt()

String str = 's' ;
char c = str.charAt( s) ;

int to Double -  conversion is automatic

int i = 345 ;
Double d = i ;

Double to int -  add cast to double

Double d = 347 ;
int i = ( Double) d ;

Other conversions can be inferred using the ideas above since those are no different ;)


 

Thursday, 9 May 2013

Setting and getting variables in a session

Data can be sent from

1. JSP to JSP
2. JSP to Servlet (or to an Action Class)
3. Servlet(or from an Action Class) to JSP
4. Servlet to Servlet (Action Class to other)

data can be either sent or retrieved in two ways

1. through Request and Response
2. through Session

here i am gonna demonstrate how to set and get variables through a session

to set a data in a session use the code below

HttpSession ses=request.getSession();
ses.setAttribute( "name", "websitejava.blogspot.com");  

here "name" is the identifier which can be any String and the "websitejava.blogspot.com"  is the actual data contained in the identifier "name".

to get data from a session use the code below

HttpSession ses=request.getSession();
ses.getAttribute( "name");

note that as in example above the getAttribute returns the data as Object, so it has to be converted to String or other respective formats before using it.

for info on how to create sessions follow this link

Wednesday, 8 May 2013

how to create a session on server

To create a session on the server just blindly follow the following code, nothing simple than this ;)

HttpSession ses=request.getSession();

the code above creates a new session if none already exists.However if there is already a session then it returns the existing session and does not create a new one.

now there is one more expression which does exactly the same.

HttpSession ses=request.getSession(true);

however, if you are interested in only getting the existing session and do not want to create a new one,then use the code below instead.

HttpSession ses=request.getSession(false);

this will return the session if there exists one,but it will not create a new one and will return null if there is none.