我正在创建一个java servlet,它应该从文本框中获取一个数字(使用HTML创建)计算其阶乘,当我按下提交按钮(也使用HTML创建)时,它应该计算并在另一个文本框中显示阶乘我创造了。
问题我已成功从第一个文本框中检索了数字(使用request.getParameter)并计算了它的阶乘。现在的问题是我无法在第二个文本框中发布计算的因子。
Plz帮助我该怎么办? 预先感谢! 这是代码: 的的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>
答案 0 :(得分:0)
将请求或会话属性中的值存储为request.setAttribute("name",value)
或session.setAttribute("name", value)
。在JSP中,使用request.getAttribute("name")
或session.getAttribute("name")