java登录和验证码判断是否填写代码
时间: 2023-12-06 17:44:56 浏览: 38
以下是一个简单的 Java 登录页面代码示例,包含验证码判断是否填写的功能:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LoginServlet extends HttpServlet {
private static final String CORRECT_CAPTCHA = "1234"; // 正确的验证码
private static final String LOGIN_PAGE = "login.jsp"; // 登录页面
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String captcha = request.getParameter("captcha");
// 判断用户名和密码是否正确
if (isValid(username, password)) {
// 验证码正确,登录成功
if (captcha != null && captcha.equals(CORRECT_CAPTCHA)) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
// 验证码不正确,跳回登录页面,并显示错误信息
request.setAttribute("error", "验证码错误,请重新输入!");
request.getRequestDispatcher(LOGIN_PAGE).forward(request, response);
}
} else {
// 用户名或密码错误,跳回登录页面,并显示错误信息
request.setAttribute("error", "用户名或密码错误,请重新输入!");
request.getRequestDispatcher(LOGIN_PAGE).forward(request, response);
}
}
private boolean isValid(String username, String password) {
// 根据实际情况编写验证逻辑
return "admin".equals(username) && "123456".equals(password);
}
}
```
在上面的代码中,我们首先获取用户提交的用户名、密码和验证码,然后调用 `isValid()` 方法进行用户名和密码的验证。如果用户名和密码正确,我们再判断验证码是否正确,如果验证码正确则将用户名保存到 HttpSession 中,并跳转到欢迎页面;如果验证码不正确,则跳回登录页面,并显示错误信息。
注意,上述代码中的验证码是硬编码在程序中的,实际应用中应该使用更安全的方式生成和校验验证码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)