我愛Java系列---【案例:使用session存儲驗證碼完成登錄功能】


image

案例需求

1. 在登錄頁面用戶登錄的時候要查看到驗證碼,如圖所示:

2. 在生成頁面驗證碼圖片的同時,使用session存儲驗證碼

3. 在處理用戶登錄請求的時候,首先校驗驗證碼

4. 校驗通過才能執行登錄操作

案例分析

image

代碼實現:

1.頁面代碼

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>login</title>
<script type="text/javascript">
function changeCode(){
document.getElementById("img").src = "/day04/checkcode?r="+new
Date().getTime();
}
</script>
</head>
<body>
<form action="/day04/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="code"></td></tr>
<!-- 通過向服務器發送請求,從服務器獲取驗證碼數據 -->
<tr><td></td><td><img id="img" src="/day04/checkcode"
onclick="changeCode();"/><a href="javascript:;" onclick="changeCode();">換一換</a>
<span><% if(request.getAttribute("msg")!=null)
{out.write(request.getAttribute("msg").toString());}%></span></td></tr>
<tr><td></td><td><input type="submit" value="登陸"></td></tr>
</table>
</form>
</body>
</html>

 

2. 配置驗證碼servlet

@WebServlet(name = "CheckcodeServlet",urlPatterns = "/checkcode")

public class CheckcodeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 創建畫布

int width = 120;

int height = 40;

BufferedImage bufferedImage = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

// 獲得畫筆

Graphics g = bufferedImage.getGraphics();

// 填充背景顏色

g.setColor(Color.white);

g.fillRect(0, 0, width, height);

// 繪制邊框

g.setColor(Color.red);

g.drawRect(0, 0, width - 1, height - 1);

// 生成隨機字符3. 登錄servlet

// 准備數據

String data =

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

// 准備隨機對象

Random r = new Random();

// 聲明一個變量 保存驗證碼

String code = "";

// 書寫4個隨機字符

for (int i = 0; i < 4; i++) {

// 設置字體

g.setFont(new Font("宋體", Font.BOLD, 28));

// 設置隨機顏色

g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

String str = data.charAt(r.nextInt(data.length())) + "";

g.drawString(str, 10 + i * 28, 30);

// 將新的字符 保存到驗證碼中

code = code + str;

}

// 繪制干擾線

for (int i = 0; i < 6; i++) {

// 設置隨機顏色

g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width),

r.nextInt(height));

}

// 將驗證碼 打印到控制台

System.out.println(code);

// 將驗證碼放到session中

request.getSession().setAttribute("code_session", code);

// 將畫布顯示在瀏覽器中

ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

3. 登錄servlet

@WebServlet(name = "LoginServlet",urlPatterns = "/login")

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {4. dao:

//用戶請求中的驗證碼獲取

String code = request.getParameter("code");

//獲取session中保存的驗證碼

String code_session =

(String)request.getSession().getAttribute("code_session");

//與session中保存的驗證碼進行校驗

if(!code_session.equalsIgnoreCase(code)){

//驗證碼錯誤,告訴用戶,頁面提示

request.setAttribute("msg","驗證碼錯誤");

request.getRequestDispatcher("/login.jsp").forward(request,response);

return;

}

//驗證碼正確,登錄邏輯執行

//獲取用戶名和密碼

String username = request.getParameter("username");

String password = request.getParameter("password");

//調用Service方法,登錄用戶

UserDao userDao = new UserDao();

User loginUser = userDao.login(username,password);

if(loginUser == null){

request.setAttribute("msg","用戶名或則密碼錯誤");

request.getRequestDispatcher("/login.jsp").forward(request,response);

return;

}else{

//登陸成功,跳轉主頁

response.sendRedirect(request.getContextPath());

return;

}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

4. dao:

public class UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

/**

* 查詢用戶名和密碼是否匹配的方法

*/

@Override

public User login(String username, String password) {

String sql = "select * from user where username = ? and password = ?";

try {

User query = template.queryForObject(sql, new

BeanPropertyRowMapper<User>(User.class), username,password);

return query;

}catch (Exception e){

e.printStackTrace();

return null;

}

}

}

session的與cookie的區別

image

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM