Saturday, 14 March 2015

Pass parameters to included jsp


We can pass parameters to the included jsp page, that is included using <jsp:include>.

Syntax
<jsp:include page="pageName" flush="true">
<jsp:param name="paramName1" value="paramValue1" />
<jsp:param name="paramName2" value="paramValue2" />
</jsp:include>

You can retrieve the parameters passed to the included jsp page using 'request.getParameter' method.

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

<%
    int radius = Integer.parseInt(request.getParameter("r"));
    String msg = request.getParameter("message");
%>

<h1><%=msg%>
    <%= getArea(radius)%>
</h1>


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>
        <%
          int radius = Integer.parseInt(request.getParameter("radius"));
        %>
        <jsp:include page="common.jsp" flush="true">
            <jsp:param name="message" value="Area of the Circle is :" />
            <jsp:param name="r" value="<%=radius%>" />
        </jsp:include>
    </body>
</html>


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
  
Two parameters 'message', 'r' are passed to included jsp file.

<jsp:include page="common.jsp" flush="true">
            <jsp:param name="message" value="Area of the Circle is :" />
            <jsp:param name="r" value="<%=radius%>" />
</jsp:include>

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment