Sunday 8 March 2015

include java code using include directive

You can define commonly used constants and functions in one file and include that file into specific jsp file. The code included using 'include' directive included at compile time.

common.jsp
<%!
    final double PI = 3.14;
    
    double getArea(int r){
        return PI*r*r;
    }
%>

common.jsp file contains, the java code to calculate area of the circle.

circle.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Area Of Circle</title>
    </head>
    <body>
        <%@ include file="common.jsp" %>
        
        <h1>Area of circle is
        <%
            int r = Integer.parseInt(request.getParameter("radius"));
        %>    
        <%=getArea(r)%>
        </h1>
    </body>
</html>

By using include tag, java code is included in 'circle.jsp' file.

<%@ include file="common.jsp" %>

index.html

<!DOCTYPE html>

<html>
    <head>
        <title>Area Of Circle</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <form method="get" action="circle.jsp">
            Enter radius <input type="text" name="radius" required="required"/><br />
            <input type="submit" />
        </form>
    </body>
</html>

Output







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment