нет расчета через html> сервлет> боб и бин> jsp - PullRequest
0 голосов
/ 04 ноября 2019

У меня есть DynamicWebApp в Eclipse с Tomcat Apache.

Моя задача: бин состоит из 2 операндов типа Integer и в виде текста арифметические операции сложение с '+', вычитание с '-' и умножениес 'MUL'. Бин возвращает результат вычисления типа Integer. Затем реализуйте следующие два сценария:

Сценарий 1: Реализация подходящего сервлета Java, который вызывает Java Bean. Вы вызываете сервлет, используя собственную HTML-страницу. Сценарий 2. Реализация подходящей страницы Java-сервера, которая повторно использует Java-бин с использованием стандартных действий JSP. Затем вызовите ваш бин со страницы JSP.

html откроется, и я могу рассчитать. после отправки ничего не открывается, но я вижу в браузере URL, что я написал. и если я запускаю jsp, то получаю: не могу найти никакой информации о свойстве (firstNum) в bean-компоненте типа (bean.CalculatorBean)

мой HTML-код называется: index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hallo Welt</title>
</head>
<body>
    <form action="HalloServlet" method="get" style="text-align: center">
        <table border="1" width="25%">
            <tr style="text-align: center">
                <td colspan="2">Rechner</td>
                <td></td>
            </tr>
            <tr>
                <td>Zahl 1</td>
                <td><input type="text" name="firstNum"></td>
            </tr>

            <tr>
                <td>Operator</td>
                <td><select name="operator">
                        <option value="+">+</option>
                        <option value="-">-</option>
                        <option value="*">MUL</option>
                </select></td>
            </tr>

            <tr>
                <td>Zahl 2</td>
                <td><input type="text" name="secondNum"></td>
            </tr>

            <tr>
                <td colspan="2"><input type="submit" value="="></td>
            </tr>
        </table>
    </form>
</body>
</html>

вызванный сервлет: HalloServlet.java

package calculator;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.CalculatorBean;

@WebServlet("/HalloServlet")
public class HalloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());

        // Get Parameter from index.html
        int operand1 = Integer.parseInt(request.getParameter("firstNum"));
        int operand2 = Integer.parseInt(request.getParameter("secondNum"));
        char operator1 = request.getParameter("operator").charAt(0);

        // Parameter from HalloServlet.java to CalculatorBean
        CalculatorBean.setFirstNum(operand1);
        CalculatorBean.setSecondNum(operand2);
        CalculatorBean.setOperator(operator1);

        // Parameter from CalculatorBean to HalloServlet.java
        CalculatorBean.getFirstNum();
        CalculatorBean.getSecondNum();
        CalculatorBean.getOperator();

        int i = Integer.parseInt(request.getParameter("result"));
        PrintWriter out = response.getWriter();
        out.println(i);
        out.flush();

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());

    }

}

вызванный компонент: CalculatorBean.java

package bean;

public class CalculatorBean {
    private int firstNum;
    private int secondNum;
    private char operator = '+';
    private int result;

    public static void getFirstNum() {
    }

    public static void setFirstNum(int firstNum) {
    }

    public static void getSecondNum() {
    }

    public static void setSecondNum(int secondNum) {
    }

    public static void getOperator() {
    }

    public static void setOperator(char operator) {
    }

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    public void calculate() {
        switch (this.operator) {
        case '+': {
            this.result = this.firstNum + this.secondNum;
            break;
        }
        case '-': {
            this.result = this.firstNum - this.secondNum;
            break;
        }
        case '*': {
            this.result = this.firstNum * this.secondNum;
            break;
        }
        }
    }

}

JSP позвонил: HalloJSP.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

</head>
<body>

    <jsp:useBean id="CalculatorBean" class="bean.CalculatorBean">
    </jsp:useBean>
    <jsp:setProperty name="CalculatorBean" property="*" />
    <%
        CalculatorBean.calculate();
    %>
    <br />
    <hr>
    <br /> Ergebnis:
    <jsp:getProperty name="CalculatorBean" property="firstNum" />
    <jsp:getProperty name="CalculatorBean" property="operator" />
    <jsp:getProperty name="CalculatorBean" property="secondNum" />
    =
    <jsp:getProperty name="CalculatorBean" property="result" />

    <br />
    <hr>
    <br />
    <form action="HalloJSP.jsp" method="post" style="text-align: center">
        <table border="1" width="25%">
            <tr style="text-align: center">
                <td colspan="2">Rechner</td>
                <td></td>
            </tr>
            <tr>
                <td>Zahl 1</td>
                <td><input type="text" name="firstNum"></td>
            </tr>

            <tr>
                <td>Operator</td>
                <td><select name="operator">
                        <option value="+">+</option>
                        <option value="-">-</option>
                        <option value="*">MUL</option>
                </select></td>
            </tr>

            <tr>
                <td>Zahl 2</td>
                <td><input type="text" name="secondNum"></td>
            </tr>

            <tr>
                <td colspan="2"><input type="submit" value="="></td>
            </tr>
        </table>
    </form>

</body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>hallowelt</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

</web-app>
...