Thursday, 20 December 2012

Formatting the Date

<%@page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Displaying Dates</title>
</head>
<body>
<h3>Displaying Today's date in different formats:</h3>
<%!
Date today=new Date();
DateFormat formatFull=DateFormat.getDateInstance(DateFormat.FULL);
DateFormat formatLong=DateFormat.getDateInstance(DateFormat.LONG);
DateFormat formatMedium=DateFormat.getDateInstance(DateFormat.MEDIUM);
DateFormat formatShort=DateFormat.getDateInstance(DateFormat.SHORT);
%>
<p>
Full Format: <%=formatFull.format(today) %>
<br>
Long Format: <%=formatLong.format(today) %>
<br>
Medium Format: <%=formatMedium.format(today) %>
<br>
Short Format: <%=formatShort.format(today) %>
</body>
</html>

Description:


  • Use the import page directive to import the java.text.package.
  • Create a Date object.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.FULL as a parameter.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.LONG as a parameter.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.MEDIUM as a parameter.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.SHORT as a parameter.
  • Pass the current date as a parameter to the format method of the FormatFull object.This will display the full date, for example: 21 December 2012.
  • Pass the current date as a parameter to the format method of the FormatLong object.This will display the long date, for example:12/21 /2012.
  • Pass the current date as a parameter to the format method of the FormatMedium object.This will display the medium date, for example:Friday, 21 December 2012.
  • Pass the current date as a parameter to the format method of the FormatShort object.This will display the short date, for example:12/21 /12.

******************************OUTPUT******************************************

Displaying Today's date in different formats:

Full Format: Friday, December 21, 2012
Long Format: December 21, 2012
Medium Format: Dec 21, 2012
Short Format: 12/21/12  


********************************************************************************

Thursday, 6 December 2012

Generating Random Numbers

     Random numbers will help you add an element  of unpredictability to your website.you can retrieve a random number and display a corresponding image, tip, or greeting.you must first create a random object  and then call the nextInt method to return a random number.

Example:

<%@page import="java.util.*" %>
<html>
<head>
<title>Generating Random Numbers</title>
</head>
<body>
<h3>Random Numbers:</h3>
<%!
Random randomValue=new Random();
%>
<p>
Random Number:<%=randomValue.nextInt() %>
<br>
Positive Random Number:<%=Math.abs(randomValue.nextInt()) %>
<br>
Generating a random Number between 1 and 6 :<%=(Math.abs(randomValue.nextInt())%5)+1 %>
<p>
<b>Note:</b>Each time this script is run a different output will be produced.
</body>
</html> 

Description:


  • Use the import page directive to import the java.util package.The Random class is located in this package.
  • Create a random object instance.
  • Call the nextInt method.The nextInt method will return a random number anywhere within the full range of integer values.Be aware that the nextInt method can return a negative number.
  • Pass the generated random number to the abs method.This will convert all generated numbers from negative to positive.
  • Use the modules operator to calculate the remainder between a positive random number and the maximum random number that you require.Add one to this result.


*****************************OUTPUT***************************************

Random Numbers:

Random Number:443353488
Positive Random Number:1446394622
Generating a random Number between 1 and 6 :2

Note:Each time this script is run a different output will be produced.
****************************************************************************



Working with Mathematical Functions

                   The Math class provides a variety of methods that can be used to perform mathematical functions.The Math class includes methods for generating random numbers, calculating square roots, and perform trigonometric functions.
                  Mathematical constants such as Pi and logarithmic E are also included in the Math class as read-only variables.These methods are stored in the java.lang.package and are automatically available in your JSP code.

Mathematical Functions:

  • sqrt(value 1)
  • pow(value 1, value 2)
  • exp(value 1)
  • log(value 1)

Trigonometric Functions:

  • sin(value 1)
  • cos(value 1)
  • tan(value 1)
  • asin(value 1)
  • acon(value 1)

Numeric Functions:

  • abs(value 1)
  • max(value 1,value 2)
  • min(value 1,value 2)
  • round(value 1)

Example :

<html>
<head>
<title>Mathematical Functions</title>
</head>
<body>
<h3>Calculating the Radius of a Circle:</h3>
<p>
The radius of a circle with a area of 500m<superscript>2</superscript> = <%=Math.sqrt(500.00/Math.PI) %>m
</body>
</html> 

Description:


This example uses the sqrt method to calculate the radius of a circle that has an area of 500msquare


*********************************OUTPUT***************************************

Calculating the Radius of a Circle:

The radius of a circle with a area of 500m2 = 12.6156626101008m 

********************************************************************************

Using Increment and Decrement Operators

              The increment operator (++) provides a shortcut to increase the value of a variable by one.The decrement operator (--) simply subtracts a value of one from a variable.The increment and decrement operators are helpful when used with loop counter variables.

<html>
<head>
<title>Increment and Decrement Operator</title>
</head>
<body>
<h3>Using Increment Operator</h3>
<%
int i=4;
%>
<p>
The value of <b>i</b> is <%=i%>
<br>
The value of <b>++i</b> is <%=++i %>
<p>
<h3>Using Decrement Operator</h3>
<p>
The value of <b>i</b> is <%=i %>
<br>
The value of <b>--i</b> is <%=--i%>
</body>
</html>

Description:

  • Assign an initial integer value to a variable.This variable will be used to illustrate the increment and decrement operators.
  • Type the increment operator (++) before the variable name and use the Expression tag to print the result to the Web page.The variable will be incremented by one before it is displayed.
  • Type the decrement operator (--) before the variable name and use the Expression tag to print the result to the Web page.The variable will be decreased by one before it is displayed.

*******************************OUTPUT****************************************

Using Increment Operator

The value of i is 4
The value of ++i is 5

Using Decrement Operator

The value of i is 5
The value of --i is 4


******************************************************************************

















Wednesday, 5 December 2012

Changing the Order of Precedence

             Multiplication and division always take precedence over addition  and subtraction when an expression is calculated. However, force parts of an expression to be calculated first with the aid of parentheses.

Example:

<html>
<head>
<title>Operator Precedence</title>
</head>
<body>
<h3>Operator Precedence</h3>
<p>
15 - 4 * 2 + 8 / 2 = <%=15-4*2+8/2 %>
<br>
(15 - 4) * 2 + 8 / 2 = <%=(15-4)*2+8/2 %>
<p>
</body>
</html>


Description:

Type an expression that includes addition,subtraction,multiplication and division.Use the expression tag to print the result to the Web page.

Place parentheses around values that need to be calculated first.Parentheses change the order of precedence.

****************************OUTPUT*******************************************

Operator Precedence

15 - 4 * 2 + 8 / 2 = 11
(15 - 4) * 2 + 8 / 2 = 26 

*******************************************************************************

Performing Basic Mathematical Operations

<html>
<head>
<title>Basic Maths Operations </title>
</head>
<body>
<h3>Addition, Subtraction, Multiplication and Division</h3>
<p>
5 + 2 = <%=5+2 %>
<br>
5 - 2 = <%=5-2 %>
<br>
5 * 2 = <%=5*2 %>
<br>
5 / 2 = <%=5/2 %>
<br>
5 % 2 = <%=5%2 %>
<p>

</body>
</html>

Description:


  • Type + between two values or variables and use the expression tag to print the result to the Web page.The + operator performs addition.
           5 + 2 = <%=5+2 %>
  • Type - between two values or variables and use the expression tag to print the result to the Web page.The + operator performs subtraction.
             5 - 2 = <%=5-2 %>
  • Type * between two values or variables and use the expression tag to print the result to the Web page.The * operator performs multiplication.
             5 * 2 = <%=5*2 %>
  • Type / between two values or variables and use the expression tag to print the result to the Web page.The / operator performs division.
            5 / 2 = <%=5/2 %>
  • Type % between two values or variables and use the expression tag to print the result to the Web page.The % operator returns the remainder when integer arithmetic is performed.
            5 % 2 = <%=5%2 %>

**********************************OUTPUT**********************************

Addition, Subtraction, Multiplication and Division

5 + 2 = 7
5 - 2 = 3
5 * 2 = 10
5 / 2 = 2
5 % 2 = 1
****************************************************************************


Using Implicit Variables

           The JSP specification defines several implicit variables that are not necessary to declare.Implicit variables or objects can only be used within scriplets and expressions.They provide a simplified way to access the Servlet API.You can use these variables to write response headers,retieve posted from data, track sessions, and handle exceptions.

Implicit JSP variables are :


Request    - Retrieves all the information that is sent from a Web browser to a Web server.

Response - Sends information back to the Web browser.

Session     - Stores and retrieves session information for each visitor to your Web Site.

Exception - Provides an exception handling mechanism.

Commenting Your Code

              Comments are used to document your code.You can use comments to explain code that is difficult to understand as well as the inner workings of any algorithms that are used.Comments provide an important communication tool between you and the programmer who will update and maintain the code at a later date.

<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Including Comments in your code</h3>
<p>
<!-- An HTML Comment -->
<%--A JSP Comment --%>
<%
// A Single line comment
for(int i=1;i<7;i++)
{
 /* A multi line comments 
 spans many lines */
 out.println("No of times this code has been repeated:"+i);
 out.println("<br>");
}
%>
</body>
</html>

Description:


  •  An HTML comment is enclosed within the <!-- and --> delimiters.HTML comments aren't displayed in a Web page, but they are included in the generated HTML source code.This can easily be accessed by anyone who views the source code in a Web browser.You should not  place any sensitive information in HTML comments.
                      <!-- An HTML Comment -->
  •  JSP comments are enclosed within the <%-- and --%> delimiters. JSP comments are not sent to the Web browser.
                   <%--A JSP Comment --%>
  • The // delimiter can be used to create a single comment line in a Scriplet tag.                                                                   
                  // A Single line comment        
  • A multi-line comment can be placed within the /*  and */ delimiters.
                          /* A multi line comments
                             spans many lines */

************************************OUTPUT***********************************

Including Comments in your code

No of times this code has been repeated:1
No of times this code has been repeated:2
No of times this code has been repeated:3
No of times this code has been repeated:4
No of times this code has been repeated:5
No of times this code has been repeated:6
*******************************************************************************

Tuesday, 4 December 2012

Using the Scriplet Tag

                       The Scriplet tag allows Java to be mixed with HTML to produce dynamic content.Java code must be embedded within the <%  and %> tag delimiters.Each language statement must end with a semicolon.

<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Embedded Java Code within a Web Page </h3>
<p>
<%
for (int i=1;i<7;i++)
{
 out.println("<H"+i+">The Size of H" + i +"</H"+i+">");
 out.println("<br>");
}
%>
</body>
</html>

Description:


  • Type <% to indicate the beginning of the Scriplet tag.
  • Type the applicable Java code after the <% delimiter.
  • Use the out.println method to generate HTML.
  • Type %> to close the Scriplet tag.

The Same program can also be written as :


<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Embedded Java Code within a Web Page </h3>
<p>
<%
for (int i=1;i<7;i++)
{
%>
 <H<%=i%>>The Size of H<%=i%> </H<%=i%>>
 <br>
<%
}
%>
</body>
</html>

you can mix HTML and Java code in any combination but you must remember to close the Scriplet tag before you start HTML and then reopen the Scriplet tag when you want to write more Java code.


*********************************OUTPUT****************************************

Embedded Java Code within a Web Page


The Size of H1



The Size of H2



The Size of H3



The Size of H4



The Size of H5


The Size of H6

********************************************************************************



Monday, 3 December 2012

Declaring Methods (Method to calculate percentages)

                A method stores a group of Java statements that you can execute from more than one location in your JSP page.This saves you from repeating the same code and allows you to update the code in a central location.You can call a methods as many times as you like.
         
              A method can accept arguments and return a result to the code from which it was called, providing greater flexibility.

Simple JSP Program Using Methods:


<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Method to calculate Percentage </h3>
<p>
<%!
float calculatePercentage(float a,float b)
{
 float result=a/b * 100;
 return result;
}
%>
<p>
Percentage of (15/20) is <%=calculatePercentage(15,20) %>%
<br>
Percentage of (10/20) is <%=calculatePercentage(10,20)%>%
<br>
Percentage of (5/20) is <%=calculatePercentage(5,20) %>%
<br>
</body>
</html>

Description:

  • Type <%! to open the declaration tag.
  • Type the keyword for the type of data that the method will return.(In the above example. "float" is used).If you type void the method will not return a value.
  • Type the name of the method(calculatePercentage)
  • Type opening and closing parentheses after the method name.({ and })
  • Declare the arguments that the method can accept.(float a, float b).A method can accept multiple arguments.
  • Insert the reusable code within braces.
             float result=a/b * 100;
             return result;
  • Type the keyword return  before the value or variable to be passed back to the calling method code.
              return result;
  • Type %> to close the declaration tag.
  • Use the Expression tag to print the result returned by the method.
  • Type the method name between the expression tag delimiters.
             calculatePercentage
  • Pass the Parameters to the method in the order that they were declared.
             <%=calculatePercentage(15,20) %>


********************************OUTPUT****************************************

Method to calculate Percentage

Percentage of (15/20) is 75.0%
Percentage of (10/20) is 50.0%
Percentage of (5/20) is 25.0% 


********************************************************************************

Declaring String Variables

A String is composed of words and characters and must be enclosed in quotation marks.A String is an object that has its own class.The String class provides methods for string manipulation.

Simple Program Using Strings:


<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Using the Declaration tag declare page level variables: </h3>
<p>
<%!
String myname;
String surname="Manikandan";
String Email,Street,City;
%>
<p>
<b>Notes:</b>The Declaration tag does not produce any output.
<p>
<%
myname="Saranya";
%>
My Name is <%=myname%> <%=surname%>
</body>
</html>

Description:

  • Type <%! to open the Declaration tag.
  • Type the String class name followed by the variable name and a semicolon.This initializes a single variable as a string object.(String myname;)
  • Use = to assign a value to the variable when it is initialized.This is explicit initialization.(String surname="Manikandan";)
  • The value assigned to a String must be enclosed in quotation marks.
  • You can initialize more than variable of same type by separating with a comma.(String Email,Street,City;)
  • Type %> to close the Declaration tag.
  • Type = to assign a value to a variable.The value must be placed on the right side of the equals sign. (myname="Saranya";)
  • Use the expression tag to print the value of a variable.(<%=myname%> <%=surname%>)


***************************OUTPUT**********************************************

Using the Declaration tag declare page level variables:

Notes:The Declaration tag does not produce any output.
My Name is Saranya Manikandan

*********************************************************************************

Declaring Integer Variables

Integers are used to store numeric data and declared with the keyword int.There are four standard types of integers, all which can holdd both positive and negativeValues.


Simple Program Using Integers:


<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Using the Declaration tag declare page level variables: </h3>
<p>
<%!
int noDays;
int year=2001;
int January, February, March;
%>
<p>
<b>Notes:</b>The Declaration tag does not produce any output.
<p>
<%
noDays=365;
%>
The Number of days in a year is <%=noDays%>
</body>
</html>

Description:

  • Type <%! to open the Declaration tag.
  • Type int followed by the variable name and a semicolon.ths declares a single variable as an integer.(int noDays;)
  • Use the equal sign(=) to assign a value to the variable when it is being initialized.This is known as explicit initialization.(int year=2001;)
  • You can initialize more than one variable of same type by separating each variable name with a comma.(int January, February, March;)
  • Type %>  to close the Declaration tag.
  • Type = sign to assign a value to a variable.The value must be placed on the right side of the equal sign.(noDays=365;)
  • Use the expression tag to print the value of a variable.(<%=noDays%>)


*************************OUTPUT*****************************************

Using the Declaration tag declare page level variables:

Notes:The Declaration tag does not produce any output.
The Number of days in a year is 365

************************************************************************** 








Declaration Tag In JSP



Declaring Variables:
Declare  an Integer - int variablename;
Declare a String  - String variablename;

<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Using the Declaration tag declare page level variables: </h3>
<p>
<%!
int year;
%>
<p>
<b>Notes:</b>The Declaration tag does not produce any output.
</body>
</html>
Description:
  • Type <! to open declaration tag.The <%! delimiter indicates the beginning  of the Declaration tag.
  • Type the data type keyword of the variable that needs to be declared.(can declare as integer or a String)
  • Type the name of the variable.
  • Type %> after the declaration.This will end the Declaration tag.
****************************Output***************************************

Using the Declaration tag declare page level variables:

Notes:The Declaration tag does not produce any output. 

**************************************************************************

Simple JSP to display Maths Functions


Simple JSP Page 2 :

<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Using Expression tag to display the result of the expression </h3>
<p>
<ul>
<li>2*6 = <%=2*6%></li>
<li>sqrt(8)=<%=Math.sqrt(8) %></li>
<li>The Current Date and time = <%=new java.util.Date() %></li>
</ul>
</body>
</html>

****************************Output***************************************

Using Expression tag to display the result of the expression

  • 2*6 = 12
  • sqrt(8)=2.8284271247461903
  • The Current Date and time = Mon Dec 03 15:32:33 CST 2012 
**************************************************************************

Simple JSP to display current date and time


Simple JSP Page 1


<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Using Expression tag to display the result of the expression </h3>
<p>
The Current date and time = <%=new java.util.Date()%>
</p>
</body>
</html>


Description:

  • Insert opening and closing  <HTML>, <HEAD>, and <BODY> tags.A JSP page must  have valid syntax.
  • Type <%= %> at the position where the date must be displayed.Java Code will be exxecuted only if it is placed within delimiters.
  • Type java.util.Date() between <%= and  %>.This will create a date object that stores the current date and time.


****************************Output*************************************

Using Expression tag to display the result of the expression

The Current date and time = Mon Dec 03 15:17:24 CST 2012

************************************************************************

Introduction to Java Server page

Java Server Pages :

                                              A JSP page is just like any other HTML file.It contains HTML formatting tags and can include client-side JavaScript,Flash animations, and Java applets.A JSP page,however, also includes Java Code and must have a .jsp extension. The extension simply indicates that the file should be executed before it is sent to the web browser.

                                            Java statements must be placed within <% and %> tag delimiters. Only code placed within these delimiters will be executed as Java code.


How a JSP page is Processed:




1.A Web browser request a JSP  page from  a Web Server. This could occur because the user has typed the address of the page or clicked on a link.

2.The Web server determines that a JSP file is being is requested by looking at the file extension.The JSP file is translated to a special Java class known as a servlet. This only occurs the first time that JSP page is requested.The Servlet is then compiled.If a JSP file has been updated, a new servlet will be generated.

3.The Servlet is then executed and the resulting HTML output is sent to the Web browser.

4.The Web browser receives the generated HTML code and displays the page. Dynamic content is displayed in the browser without the need for the user to install any additional software.