자바 세 션 인증 코드 사례 코드 인 스 턴 스 분석
사용자 가 사용자 이름,비밀번호,인증 코드 를 입력 하 십시오.
사용자 이름과 비밀번호 입력 이 잘못 되면 로그 인 페이지 로 이동 합 니 다.알림:사용자 이름 이나 비밀번호 오류
인증 코드 입력 이 잘못 되면 로그 인 페이지 로 이동 합 니 다.알림:인증 코드 오류
모든 입력 이 정확 하 다 면 홈 페이지 success.jsp 로 이동 합 니 다.표시:사용자 이름,생각 을 환영 합 니 다.
인증 코드 를 생 성 할 때 값 을 session 에 저장 하고 비교 할 때 꺼 내 비교 합 니 다.
코드 index.jsp
<%--
Created by IntelliJ IDEA.
User: tanglei
Date: 2020/6/26
Time: 12:48
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="/login_time_war_exploded/checkCode?time="+new Date().getTime();
}
}
</script>
<style>
div{
color: red;
}
</style>
</head>
<body>
<form action="/login_time_war_exploded/login" 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="/login_time_war_exploded/checkCode"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" "></td>
</tr>
</table>
</form>
<div><%=request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error")%></div>
<div><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error") %></div>
</body>
</html>
success.jsp
<%--
Created by IntelliJ IDEA.
User: tanglei
Date: 2020/6/26
Time: 6:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1><%=request.getSession().getAttribute("user")%>, </h1>
</body>
</html>
인증번호 checkCode.java
package cn.guizimo.servlet;
import javax.imageio.ImageIO;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 100;
int height = 50;
//
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//
Graphics g = image.getGraphics();
//
g.setColor(Color.PINK);
g.fillRect(0, 0, width, height);
//
g.setColor(Color.BLUE);
g.drawRect(0, 0, width - 1, height - 1);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random ran = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
char ch = str.charAt(index);
sb.append(ch);
g.drawString(ch+"",width/5*i,height/2);
}
String checkCode_session = sb.toString();
// session
req.getSession().setAttribute("checkCode_session",checkCode_session);
//
g.setColor(Color.GREEN);
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2= ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//
ImageIO.write(image, "jpg", resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
login.java
package cn.guizimo.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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class Login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. request
req.setCharacterEncoding("utf-8");
//2.
String username = req.getParameter("username");
String password = req.getParameter("password");
String checkCode = req.getParameter("checkCode");
//3.
HttpSession session = req.getSession();
String checkCode_session = (String) session.getAttribute("checkCode_session");
// session
//session.removeAttribute("checkCode_session");
//3.
if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkCode)){
//
//
//
if("zhangsan".equals(username) && "123".equals(password)){// UserDao
//
// ,
session.setAttribute("user",username);
// success.jsp
resp.sendRedirect(req.getContextPath()+"/success.jsp");
}else{
//
// request
req.setAttribute("login_error"," ");
//
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}else{
//
// request
req.setAttribute("cc_error"," ");
//
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
테스트 로그 인 인터페이스인증번호 오류
사용자 이름 비밀번호 오류
로그 인 성공
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.