案例:验证码的实现 案例重点:理解重定向和服务器转发的区别 使用session存储和取出数据
登录页面
<%--
Created by IntelliJ IDEA.
User: bed
Date: 2021/10/26
Time: 20:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
<script>
window.onload=function () {
document.getElementById("img").onclick=function () {
this.src="/day16/CheckcodeDemo04?time="+new Date().getTime();
}
}
</script>
<style>
div{color: coral}
</style>
</head>
<body>
<form action="/day16//LoginServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" name="checkcode"></td>
</tr>
<tr>
<td colspan="2"><img id="img" src="/day16/CheckcodeDemo04"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
</form>>
<div><%=request.getAttribute("checkcode error")%></div>
<div><%=request.getAttribute("namepass error")%></div>
</body>
</html>
服务器内容
package cn.bed.checkcodeV;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkcode = request.getParameter("checkcode");
HttpSession session=request.getSession();
String checkcode_session = (String) request.getSession().getAttribute("checkCode_session");
if(checkcode_session.equalsIgnoreCase(checkcode)){
if("bed".equals(username)&&"bed123".equals(password)){
session.setAttribute("user",username);
response.sendRedirect(request.getContextPath()+"/success.jsp");
}else{
request.setAttribute("namepass error","用户名或密码错误");
request.getRequestDispatcher("/Login.jsp").forward(request,response);
}
}else{
request.setAttribute("checkcode error","验证码错误");
request.getRequestDispatcher("/Login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}