1.生成驗證碼Servlet

1 package com.isit.servlet; 2 3 import javax.imageio.ImageIO; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpSession; 10 import java.awt.*; 11 import java.awt.image.BufferedImage; 12 import java.io.IOException; 13 import java.util.Random; 14 15 @WebServlet("/checkCodeServlet") 16 public class CheckCodeServlet extends HttpServlet { 17 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 18 19 20 int width = 100; 21 int height = 50; 22 23 //1.創建一對象,在內存中圖片(驗證碼圖片對象) 24 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 25 26 27 //2.美化圖片 28 //2.1 填充背景色 29 Graphics g = image.getGraphics();//畫筆對象 30 g.setColor(Color.PINK);//設置畫筆顏色 31 g.fillRect(0, 0, width, height); 32 33 //2.2畫邊框 34 g.setColor(Color.BLUE); 35 g.drawRect(0, 0, width - 1, height - 1); 36 37 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789"; 38 //生成隨機角標 39 StringBuffer sb = new StringBuffer(); 40 Random ran = new Random(); 41 for (int i = 1; i <= 4; i++) { 42 int index = ran.nextInt(str.length()); 43 //獲取字符 44 char ch = str.charAt(index);//隨機字符 45 sb.append(ch); 46 //2.3寫驗證碼 47 g.drawString(ch + "", width / 5 * i, height / 2); 48 } 49 String checkCode = sb.toString(); 50 HttpSession session = request.getSession(); 51 session.setAttribute("checkCode", checkCode); 52 //2.4畫干擾線 53 g.setColor(Color.GREEN); 54 55 //隨機生成坐標點 56 57 for (int i = 0; i < 10; i++) { 58 int x1 = ran.nextInt(width); 59 int x2 = ran.nextInt(width); 60 61 int y1 = ran.nextInt(height); 62 int y2 = ran.nextInt(height); 63 g.drawLine(x1, y1, x2, y2); 64 } 65 66 67 //3.將圖片輸出到頁面展示 68 ImageIO.write(image, "jpg", response.getOutputStream()); 69 70 71 } 72 73 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 74 this.doPost(request, response); 75 } 76 }
2.登陸Servlet

1 package com.isit.servlet; 2 3 import com.isit.dao.UserDao; 4 import com.isit.entity.User; 5 import org.apache.commons.beanutils.BeanUtils; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import javax.servlet.http.HttpSession; 13 import java.io.IOException; 14 import java.lang.reflect.InvocationTargetException; 15 import java.util.Map; 16 17 /** 18 * @program: LoginServlet 19 * @description: 登陸 20 * @author: wxh 21 * @date: 2019-06-11 15:03 22 **/ 23 @WebServlet("/loginServlet") 24 public class LoginServlet extends HttpServlet { 25 @Override 26 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 27 this.doPost(req, resp); 28 } 29 30 @Override 31 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 32 req.setCharacterEncoding("utf-8"); 33 //1.驗證驗證碼是否正確 34 HttpSession session = req.getSession(); 35 String checkCode = (String) session.getAttribute("checkCode"); 36 //1.1.驗證碼錯誤 37 String code = req.getParameter("checkCode"); 38 if (checkCode != null && !checkCode.equalsIgnoreCase(code)) { 39 req.setAttribute("msg", "驗證碼錯誤"); 40 req.getRequestDispatcher("/index.jsp").forward(req, resp); 41 } else { 42 //1.2.驗證碼正確 43 //2.校驗登陸密碼 44 User user = new User(); 45 Map<String, String[]> parameterMap = req.getParameterMap(); 46 //使用BeanUtils工具類封裝成JavaBean對象 47 try { 48 BeanUtils.populate(user, parameterMap); 49 } catch (IllegalAccessException e) { 50 e.printStackTrace(); 51 } catch (InvocationTargetException e) { 52 e.printStackTrace(); 53 } 54 UserDao userDao = new UserDao(); 55 User entity = userDao.checkUser(user); 56 if (entity != null) { 57 //2.1.匹配重定向到登錄成功 Success.jsp 頁面 58 session.setAttribute("username", entity.getUsername()); 59 resp.sendRedirect(req.getContextPath() + "/success.jsp"); 60 } else { 61 //2.2.不匹配,轉發到登陸界面 62 req.setAttribute("msg", "用戶名或密碼錯誤"); 63 req.getRequestDispatcher("/index.jsp").forward(req, resp); 64 } 65 } 66 } 67 }
3.JavaBean實體類代碼

1 package com.isit.entity; 2 3 /** 4 * @program: User 5 * @description: User實體類 6 * @author: wxh 7 * @date: 2019-06-11 14:15 8 **/ 9 public class User { 10 private String id; 11 private String username; 12 private String password; 13 14 public String getId() { 15 return id; 16 } 17 18 public void setId(String id) { 19 this.id = id; 20 } 21 22 public String getUsername() { 23 return username; 24 } 25 26 public void setUsername(String username) { 27 this.username = username; 28 } 29 30 public String getPassword() { 31 return password; 32 } 33 34 public void setPassword(String password) { 35 this.password = password; 36 } 37 }
4.UserDao數據庫操作層

1 package com.isit.dao; 2 3 import com.isit.entity.User; 4 import com.isit.utils.JDBCUtils; 5 import org.springframework.jdbc.core.JdbcTemplate; 6 import org.springframework.jdbc.core.RowMapper; 7 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 11 /** 12 * @program: UserDao 13 * @description: UserDao 14 * @author: wxh 15 * @date: 2019-06-11 14:46 16 **/ 17 public class UserDao { 18 JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource()); 19 20 public User checkUser(User user){ 21 String sql = "select * from user where username = ? and password = ?"; 22 try{ 23 User entity= jdbcTemplate.queryForObject(sql, new RowMapper<User>() { 24 @Override 25 public User mapRow(ResultSet resultSet, int i) throws SQLException { 26 User user = new User(); 27 String username = resultSet.getString("username"); 28 String password = resultSet.getString("password"); 29 user.setUsername(username); 30 user.setPassword(password); 31 return user; 32 } 33 },user.getUsername(),user.getPassword()); 34 return entity; 35 }catch (Exception e){ 36 e.printStackTrace(); 37 return null; 38 } 39 } 40 41 }
5.JDBC工具類

1 package com.isit.utils; 2 3 import com.alibaba.druid.pool.DruidDataSourceFactory; 4 5 import javax.sql.DataSource; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.sql.Connection; 9 import java.sql.ResultSet; 10 import java.sql.SQLException; 11 import java.sql.Statement; 12 import java.util.Properties; 13 14 /** 15 * @program: JDBCUtils 16 * @description: 數據庫連接池工具類 17 * @author: wxh 18 * @date: 2019-06-11 14:17 19 **/ 20 public class JDBCUtils { 21 22 private static DataSource ds; 23 static { 24 Properties properties = new Properties(); 25 InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); 26 try { 27 properties.load(resourceAsStream); 28 ds = DruidDataSourceFactory.createDataSource(properties); 29 } catch (IOException e) { 30 e.printStackTrace(); 31 }catch (Exception e) { 32 e.printStackTrace(); 33 } 34 } 35 36 public static DataSource getDataSource(){ 37 return ds; 38 } 39 40 public static Connection getConnection() throws SQLException { 41 return ds.getConnection(); 42 } 43 44 public static void close(Connection con, Statement statement, ResultSet resultSet){ 45 if(resultSet !=null){ 46 try { 47 resultSet.close(); 48 } catch (SQLException e) { 49 e.printStackTrace(); 50 } 51 } 52 if(statement!=null){ 53 try { 54 statement.close(); 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } 58 } 59 if(con!=null){ 60 try { 61 con.close(); 62 } catch (SQLException e) { 63 e.printStackTrace(); 64 } 65 } 66 } 67 68 public static void close(Connection connection,Statement statement){ 69 close(connection,statement,null); 70 } 71 72 }
6.JSP頁面

1 <%-- 2 Created by IntelliJ IDEA. 3 User: isit 4 Date: 2019/6/11 5 Time: 14:09 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <html> 10 <head> 11 <title>登陸</title> 12 <script> 13 window.onload= function () { 14 document.getElementById("img").onclick=function () { 15 this.src = "/loginJsp/checkCodeServlet?time="+ new Date().getTime(); 16 } 17 } 18 </script> 19 </head> 20 21 <body> 22 <form method="post" action="/loginJsp/loginServlet"> 23 <div>登錄名:<input type="text" name="username"></div> 24 <div>密 碼:<input type="password" name="password"></div> 25 <div><img src="/loginJsp/checkCodeServlet" id="img"></div> 26 <div> <input type="text" name="checkCode"></div> 27 <div><input type="submit"></div> 28 </form> 29 <div><%=request.getAttribute("msg")%></div> 30 </body> 31 </html>

1 <%-- 2 Created by IntelliJ IDEA. 3 User: isit 4 Date: 2019/6/11 5 Time: 16:11 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <html> 10 <head> 11 <title>登陸成功</title> 12 </head> 13 <body> 14 <h1> 15 <%=request.getSession().getAttribute("username")%> ,登陸成功 16 </h1> 17 </body> 18 </html>
總結:
1.實現登陸操作需要驗證碼Servlet和登陸Servlet兩個Servlet,一個會話中需要請求兩次,一個生成驗證碼圖片,一個做驗證操作(驗證碼匹配和登陸賬號密碼匹配);
2.CheckCodeServlet生成驗證碼圖片到index.jsp頁面,並將生成的驗證碼存到session中,以供LoginServlet做驗證碼驗證操作;
3.LoginServlet需要兩步驗證,(1)驗證驗證碼(2)驗證登陸名和密碼
3.1.通過HttpServletRequst對象獲取Session對象,從Session對象中獲取CheckCodeServlet添加到session中的驗證碼,以做驗證操作,成功,繼續下一步的登陸名和密碼操作,失敗,轉發到登陸index.jsp頁面,提示驗證碼錯誤;
3.2.驗證碼校驗通過后,通過Dao層操作數據庫返回查詢結果(使用Druid數據庫連接池,並使用JDBCTemple對數據庫連接池對象進行封裝,執行queryForObject方法返回實體類User)
3.3.校驗通過,設置登陸名到session中(setAttribute),重定向到success.jsp頁面,jsp頁面取session中存放的登錄名,展示XXX,登陸成功;
3.4.校驗失敗,轉發到index.jsp頁面中,提示登陸名密碼錯誤。