在Tomcat中创建Servlet程序,随机生成一个五位数
时间: 2023-05-21 19:05:44 浏览: 121
随机数生成程序
5星 · 资源好评率100%
的验证码并在页面上展示,你知道如何实现吗?
可以通过以下代码实现:
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String captcha = generateCaptcha();
request.getSession().setAttribute("captcha", captcha);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>随机生成验证码</title></head>");
out.println("<body>");
out.println("<h2>验证码是:" + captcha + "</h2>");
out.println("</body>");
out.println("</html>");
}
private String generateCaptcha() {
Random random = new Random();
String captcha = "";
for (int i = 0; i < 5; i++) {
captcha += String.valueOf(random.nextInt(10));
}
return captcha;
}
}
```
当请求 `/captcha` 路径时会触发 `doGet` 方法,在该方法中生成一个随机的五位数的验证码,并将其保存在当前会话中,随后将其展示在页面中。请注意本示例中并未进行验证码的校验,实际应用中需要进行相应的处理来确保验证码的有效性。
阅读全文