首先是用户需求:
1.输入用户名密码验证码
2.登录成功跳转success.jsp,展示username,欢迎您
3.登录失败跳转回登录页面
*如账号或密码错误,提示账号或密码错误
*如验证码错误,提示验证码错误
程序编写流程:
1.编写login.html登录页面
username & password & 验证码输入 三个输入框
2.编写验证码的servlet,可以参考我4月20日编写的《随机验证码生成》
3.编写LoginServlet,含有获取验证码、用户封装、判断用户名密码验证码是否一致
*先不调用数据库,直接拿输出数据与字符判断,如成功,在进行连接调用数据库判断
4.若程序运行成功,使用Druid数据库连接池技术,操作mysql,
5.使用JDBCTemplate技术封装JDBC
6.编写操作数据表中User表的Uerdao类
7.改写刚刚为了方便,进行账号密码直接判断的程序,调用Uerdao类进行判断
8.输入用户名密码验证码
9.登录成功跳转success.jsp,展示username,欢迎您
10.登录失败跳转回登录页面
*如账号或密码错误,提示账号或密码错误
*如验证码错误,提示验证码错误
首先是login.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>login
然后是编写的验证码的servlet,需要注意的是需要将随机生成的验证码字符存入session,与输入的进行判断
package cn.stormtides.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("/checkCodeServlet") public class CheckCodeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 100; int height = 50; //1.创建一对象,在内存中图片(验证码图片对象) BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //2.美化图片 //2.1 填充背景色 Graphics g = image.getGraphics();//画笔对象 g.setColor(Color.PINK);//设置画笔颜色 g.fillRect(0,0,width,height); //2.2画边框 g.setColor(Color.BLUE); g.drawRect(0,0,width - 1,height - 1); String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789"; //生成随机角标 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); //2.3写验证码 g.drawString(ch+"",width/5*i,height/2); } String checkCode_session = sb.toString(); //将验证码存入session request.getSession().setAttribute("checkCode_session",checkCode_session); //2.4画干扰线 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); } //3.将图片输出到页面展示 ImageIO.write(image,"jpg",response.getOutputStream()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
然后为最主要的loginServlet.java,因为没有调用数据库,就直接和字符:"zhangsan","123"比较,在运行成功后对调用数据库进行判断
package cn.stormtides.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("/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) session.getAttribute("checkCode_session"); //删除session中存储的验证码 session.removeAttribute("checkCode_session"); //忽略大小写比较验证码 if (checkCode_session.equalsIgnoreCase(checkCode)){ //验证码正确 if ("zhangsan".equals(username)&&"123".equals(password)){ //登陆成功 //存储信息,用户信息 session.setAttribute("user",username); //重定向到success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); }else{ //登录失败 //存储提示信息到request request.setAttribute("login_error","用户名或密码错误"); //转发到登录页面 request.getRequestDispatcher("/login.jsp").forward(request,response); } }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); } }
在运行成功后,进行数据库的有关操作
首先在数据库中创建User表,
CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) UNIQUE NULL, PASSWORD VARCHAR(32) NOT NULL ); INSERT INTO USER(username,PASSWORD)VALUES ('superbaby','123');
首先创建用户实体类User.java
package cn.stormtides.domain; //用户实体类 public class User { private int id; private String username; private String 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 + '\'' + '}'; } }
再进行编写操作数据表中User表的类,依赖于Druid连接池与Template
package cn.stormtides.dao; import cn.stormtides.domain.User; import cn.stormtides.util.JDBCUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; /** * 操作数据表中User表的类 */ public class UserDao { private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource()); /** * 登录方法 * @param loginUser * @return user */ public User login(User loginUser){ try{ //编写sql String sql="select * from user where username= ? and password=?"; //调用query方法 User user = template.queryForObject(sql, new BeanPropertyRowMapper(User.class), loginUser.getUsername(), loginUser.getPassword()); return user; }catch (DataAccessException e){ e.printStackTrace(); return null; } } }
编写JDBC工具类,使用Druid连接池
package cn.stormtides.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; public class JDBCUtils { private static DataSource ds; static { try { //加载配置文件 Properties pro=new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); }catch (IOException e){ e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } /** * 获取连接池对象 */ public static DataSource getDataSource(){ return ds; } /** * 获取连接Connection对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } }
配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/day14 username=root password=root initialSize=5 maxAction=10 maxWait=3000
最后改动LoginServlet.java文件调用页面输入的账号密码验证码与数据库中的中的比较,就可以了
程序的原始代码https://github.com/StormTides/reference/tree/master/day16_loginTest