Saturday, 14 March 2015

jsp Declarations


Declarations are like scriptlets but difference is, scriptlet code is part of _jspService() method, where as declaration code exist outside of _jspService().
Syntax
<%! statement1
statement2
statementN
%>

You can declare instance, class varaibles, methods and inner classes inside declarations.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*" %>
        

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Nth Prime Number</title>
    </head>
    <body>
        <%-- Declarations --%>
        <%!
            public static int nthPrime(int n) {
                int candidate, count;
                for(candidate = 2, count = 0; count < n; ++candidate) {
                    if (isPrime(candidate)) {
                        ++count;
                    }
                }
                return candidate-1;
            }
    
            private static boolean isPrime(int n) {
                for(int i = 2; i < n; ++i) {
                    if (n % i == 0) {
                        return false;
                    }
                }
                return true;
            }
        %>
        
        <%
            Random rand = new Random();
            int n = rand.nextInt(100);
        %>
        <h1>
            <%= n %>th prime number is
            <%= nthPrime(n) %>
        </h1>
    </body>
</html>


Output
 
Note:
You can access implicit objects of JSP from scriptlets, but you can't access implicit objects from declarations.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment