本帖最后由 980041382 于 2021-11-13 21:10 编辑
[Java] 纯文本查看 复制代码 package com.web;
import com.domain.Computer;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/handleComputerServlet")
public class HandleComputerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double num1 = Double.parseDouble(request.getParameter("num1"));
String operator = request.getParameter("operator");
double num2 = Double.parseDouble(request.getParameter("num2"));
Computer computer = new Computer();
HttpSession session = request.getSession();
if (num2!=0){
switch (operator) {
case "+":
computer.setResult(num1 + num2);
break;
case "-":
computer.setResult(num1 - num2);
break;
case "*":
computer.setResult(num1 * num2);
break;
case "/":
computer.setResult(num1 / num2);
break;
}
}else{
switch (operator) {
case "+":
computer.setResult(num1 + num2);
break;
case "-":
computer.setResult(num1 - num2);
break;
case "*":
computer.setResult(num1 * num2);
break;
case "/":
session.setAttribute("result", "被除数不能为0");
break;
}
}
response.sendRedirect("lookResult.jsp");
}
}
我需要转发计算结果保存到Computer这个实体类里面 然后再在JSP页面调用这个结果
补充一下lookResult的代码
[JavaScript] 纯文本查看 复制代码 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.domain.Computer" %>
<jsp:useBean id="computer" class="com.domain.Computer" scope="session"/>
<jsp:setProperty name="computer" property="*"/>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1><b>结果是:<jsp:getProperty name="computer" property="result"/></b></h1>
<h1><b>${result}</b></h1>
</body>
</html>
补充一下inputNumber的代码
[JavaScript] 纯文本查看 复制代码 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/handleComputerServlet" method="post">
<input type="text" name="num1" width="50px" />
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="num2" width="50px"/>
<input type="submit" value="计算"/>
</form>
</body>
</html>
|