## Case: Captcha
1. Case Requirements:
1. Access the login page with the code of the login.jsp
2. user to enter a user name, password and a verification code.
* If the username and password entered incorrectly, skip the login page Note: user name or password is incorrect
* If the code is entered incorrectly, jump login page Tip: Codes error
* If all input is correct, then jump to the home page success.jsp, displayed: user name, you are welcome
2. Analysis:
package domain; /** * 用户 实体类 */ public class User { private int id; private String username; private String password; public User() { } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
package util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * JDBC工具类 druid */ public class JDBCUtils { private static DataSource ds; static { try { //1.加载配置文件 Properties properties = newThe Properties (); // use ClassLoader load profile, obtaining input stream of bytes the InputStream resourceAsStream = JDBCUtils. Class .getClassLoader () the getResourceAsStream ( "druid.properties." ); Properties.load (resourceAsStream); // 2. initial connection pool object DS = DruidDataSourceFactory.createDataSource (Properties); } the catch (IOException E) { e.printStackTrace (); } the catch (Exception E) { e.printStackTrace (); } } / ** * Get Connection object * / public staticThe getConnection Connection () throws SQLException { return ds.getConnection (); } / ** * Gets connection pool object * / public static the DataSource getDataSource () { return DS; } }
Package DAO; Import domain.User; Import org.springframework.dao.DataAccessException; Import org.springframework.jdbc.core.BeanPropertyRowMapper; Import org.springframework.jdbc.core.JdbcTemplate; Import util.JDBCUtils; / ** * database operations user table class * * / public class UserDao { // declare JDBCTemplate object shared Private the JdbcTemplate the jdbcTemplate = new new the JdbcTemplate (JDBCUtils.getDataSource ()); / ** * Log method * @param loginUser and only the user password * @returnuser returns the user all the information * / public the User the Login (the User loginUser) { the try { String SQL = "the SELECT * from the WHERE user = username and password =??" ; // result is package query the USER the User user = jdbcTemplate. queryForObject (SQL, new new BeanPropertyRowMapper <the User> (the User. class ), loginUser.getUsername (), loginUser.getPassword ()); return User; } the catch (the DataAccessException E) { e.printStackTrace (); return null ; } } }
package web.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 javax.servlet.http.HttpSession; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; /** 验证码 案例 */ @WebServlet( "/checkCodeServlet") Public class CheckCodeServlet the extends the HttpServlet { protected void the doPost (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { // 1. Create an object image stored in memory int width = 100 ; int heigth = 50 ; the BufferedImage Image = new new the BufferedImage (width, heigth, BufferedImage.TYPE_INT_RGB); // 2. beautify the picture // 2.1 fill the background color Graphics Graphics = image.getGraphics (); // Paintbrush Object graphics.setColor (Color.PINK); // Set brush color graphics.fillRect (0,0, width, heigth); // filled rectangle // 2.2 Videos border graphics.setColor (Color.BLUE); as graphics.drawRect ( 0 , 0,. 1-width,-heigth. 1); // because the brush has to be reduced so that a 1px @ 2.3 fill codes String STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ; the StringBuilder img_str = new new the StringBuilder (); // for storing codes information of the Random Random = new new the Random (); for ( int i = 1; i <=4 ; i++) { int index = random.nextInt(str.length()); graphics.drawString(str.charAt(index)+"",width/5*i,heigth/2); img_str.append(str.charAt(index)); } HttpSession session = request.getSession(); session.setAttribute("checkCode_session",img_str.toString()); //2.4画干扰线 graphics.setColor(Color.green); for (int i = 0; i <10 ; i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(heigth); int y2 = random.nextInt(heigth); graphics.drawLine(x1,y1,x2,y2); } //3.将图片输出至页面展示 ImageIO.write(image,"jpg",response.getOutputStream()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
package web.servlet; import dao.UserDao; import domain.User; import org.apache.commons.beanutils.BeanUtils; 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; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.设置编码 request.setCharacterEncoding("utf-8"); //2.获取请求参数 String login_username = request.getParameter("username"); String login_password = request.getParameter("password"); String login_checkCode = request.getParameter("checkCode"); //3.获取验证码 = Session the HttpSession Request.getSession (); String checkCode_session = (String) session.getAttribute ( "checkCode_session" ); // delete the session codes stored in session.removeAttribute ( "checkCode_session" ); // 4. Analyzing whether codes case-insensitive comparison correct iF (login_checkCode =! null && checkCode_session.equalsIgnoreCase (login_checkCode)) { // 5. the code is correct username and password are correct Analyzing the User loginUser = new new the User (); loginUser.setUsername (login_username); loginUser. the setPassword (login_password); UserDao userDao =new new UserDao (); the User the User = userDao.login (loginUser); IF (the User == null ) { // Login failed // stored message to the Request request.setAttribute ( "login_error", "user name or password is incorrect" ) ; // forwarded to the login page request.getRequestDispatcher ( "/ the login.jsp" ) .forward (Request, the Response); } the else { // successful login // store information, because the user information user information can span many pages, so use session without using the Request session.setAttribute ( "the User",user.getUsername()); //重定向到success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); } }else{ request.setAttribute("cc_error","验证码错误"); //验证码错误 request.getRequestDispatcher("login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
<% @ Page contentType = "text / HTML; charset = UTF-8" Language = "the Java"%> <HTML> <head> <title> Log Case </ title> ! <- Analysis: Click on the image, the need for a 1 . hyperlinks and pictures to bind the click event 2 . reset the image src attribute value -> <Script> the window.onload = function () { document.getElementById ( "img") onclick =. function ( ) { the this .src = "? $ {} pageContext.request.contextPath / checkCodeServlet" + new new a Date () the getTime ();. } } </ Script> </ head> <body> <form action="${pageContext.request.contextPath}/loginServlet" method="post"> <table> <tr> <td>用户名</td> <td><input type="text" placeholder="请输入用户名" name="username"></tr></td> <tr> <td>密码</td> <td><input type="text" placeholder="请输入用户密码" name="password"></td> </tr> <tr > <td>验证码</td> <td><input type="text"placeholder = "Please enter PIN" name = "checkCode"> </ TD> <TR> </ TR> <td colspan="2"><img id="img" src="${pageContext.request.contextPath}/checkCodeServlet"></td> </tr> <tr> <td colspan="2"><input type="submit" value="登录"></td> </tr> </table> </form> ${requestScope.cc_error} ${requestScope.login_error} </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录成功页面</title> </head> <body> <% HttpSession session1 = request.getSession(); String user = (String) session1.getAttribute("user"); out.print(user+"欢迎登录"); %> </body> </html>