Here is another JSP program to check leap year, you will learn the below JSP tricks from this program:
1. Retrieve the value from HTML form in JSP.
2. Check if the entered value is numeric in JSP.
3. Convert string to integer in JSP.
4. Using multiple IF Conditions in JSP.
JSP script to find leap year:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Program to find Leap year</title> </head> <body> <h2>JSP Program to check Leap year or not - Script by <a href="http://www.tutorialsmade.com/">Tutorialsmade.com</a></h2> <form action="" method="post"> <input type="text" name="year" /> <input type="submit" /> </form> </body> </html> <% //check if post request if("POST".equalsIgnoreCase(request.getMethod())) { //define variables String year; int yearint; Boolean isnum; //get the entered year from text box year = request.getParameter("year"); //check if entered is a number isnum = year.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+"); //if it is number then allow if(isnum) { //change string to int yearint = Integer.parseInt(year); //three conditions to find out the leap year if( (0 == yearint % 4) && (0 != yearint % 100) || (0 == yearint % 400) ) { out.print("<p>"+year+" is a leap year"); } else { out.print("<p>"+year+" is not a leap year"); } }else{ out.println("<p>Please enter numbers only</p>"); } } %> |
The code is self explanatory, read the comments in the script. This is a single page JSP web application, not a JSP & Servlet web application.
To find the leap year, these are the conditions,
1. Year should be evenly divisible by 4 (year % 4 == 0)
2. AND (&&) Year should not be evenly divisible by 100 (year % 100 != 0)
3. OR (||) year should be evenly divisible by 400 (Year % 400 == 0)
if both the 1st AND 2nd condition is true OR 3rd is true then it is a Leap year.
Enjoy learning. Good luck.