0

我正在创建一个 java servlet,它应该从文本框中获取一个数字(使用 HTML 创建)计算其阶乘,当我按下提交按钮(也使用 HTML 创建)时,它应该计算并在我创建的另一个文本框中显示阶乘.

问题我已成功从第一个文本框中检索到数字(使用 request.getParameter)并计算出阶乘。现在的问题是我无法在第二个文本框中发布计算出的阶乘。

请帮助我我该怎么办?预先感谢!这是代码: servlet:

package factorial;

import java.io.*;

import javax.servlet.Servlet;
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 org.apache.jasper.tagplugins.jstl.core.Out;

/**
 * Servlet implementation class fact
 */
@WebServlet("/fact")
public class fact extends HttpServlet implements Servlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public fact() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        long number = Long.parseLong((request.getParameter("num")));
        long fact=1;
        while(number>1){
            fact=fact*number;
            number--;
        }

        //request.setAttribute("factorial", fact); //***this is not working***
        //out.println(fact);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

HTML 代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="get">
    Enter a number: <input type="text" name="num">
    <input type="submit"/>
    Factorial <input type="text" id="factorial" name="factorial"/>
</form>
</body>
</html>
4

1 回答 1

0

将请求或会话属性中的值存储为request.setAttribute("name",value)session.setAttribute("name", value)。在 JSP 中,使用request.getAttribute("name")or检索它们session.getAttribute("name")

于 2013-09-20T12:34:34.323 回答