繁体   English   中英

从另一个jsp文件调用JSP函数

[英]Calling a JSP Function from another jsp file

我已经在jsp上创建了一个简单的应用程序。

在我的全局函数jsp文件中,我创建了如下函数:

<%! public double calcB(double w, double h){
                double B = 0;

                return B = (w / (h * h));

            }


            public String calcClassif(double B){
                String classifi = null;

                  if(B >= 30)
                      classif = "Obese";
                  else if(B >= 25)
                      classif = "Overweight";
                  else if(B >= 18.5)
                      classif = "Normal";
                  else 
                      classif = "Underweight";

                  return classif;

            }

        %>

现在在我的index.jsp文件中,我编写了以下内容:

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

        <% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
           double we = 0, he = 0;
           if(submitted){

               weight = Double.parseDouble(request.getParameter("w"));
               height = Double.parseDouble(request.getParameter("h"));                                 
           }
        %>

        <h3>BMI Calculator</h3>

        <form action = "index.jsp" method = "post">
            <input type ="hidden" name = "isSubmitted" value = "true"> 
            Weight: <input type = "text" name = "w"> <br> <br>
            Height: <input type = "text" name = "h"> <br> <br>
            <input type = "submit" value = "Compute"> <br> <br>

            BMI: <%= calcBMI(we, he) %> <br> <br>
            Classification: <%= classification %>
    </form>

当我执行应用程序时,分类不起作用。如何调用该方法向我显示正确的分类? 请帮助..谢谢

您永远不会为classification指定值。 您可以尝试以下方法:

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

        <% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
           double we = 0, he = 0;
           if(submitted){
               weight = Double.parseDouble(request.getParameter("w"));
               height = Double.parseDouble(request.getParameter("h"));
               bmi = calcBMI(we, he);
               classification = calcClassif(bmi);
           }
        %>

        <h3>BMI Calculator</h3>

        <form action = "index.jsp" method = "post">
            <input type ="hidden" name = "isSubmitted" value = "true"> 
            Weight: <input type = "text" name = "w"> <br> <br>
            Height: <input type = "text" name = "h"> <br> <br>
            <input type = "submit" value = "Compute"> <br> <br>

            BMI: <%= bmi %> <br> <br>
            Classification: <%= classification %>
    </form>

每当您的servlet容器编译JSP时,每次都会以不同的名称进行编译。 这使得很难在另一个JSP页面中使用JSP页面功能。 我建议您开始使用servlet和POJO来满足您的数据处理需求。

无论如何,您没有任何名为classification (index.jsp:21)的变量,因此不会显示该变量,并且服务器会将错误记录到控制台,而不是像PHP这样的客户端。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM