在Tomcat容器中,创建Servlet程序,实现5位随机数字;
时间: 2023-05-21 08:05:42 浏览: 104
可以使用Java的Random类生成随机数,然后将其转换为5位数字。以下是示例代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RandomServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>5位随机数字:</h3>");
Random random = new Random();
int num = random.nextInt(100000);
String numStr = String.format("%05d", num);
out.println(numStr);
out.println("</body></html>");
}
}
注意,需要将该Servlet部署到Tomcat容器中,并配置相应的web.xml文件。
阅读全文