带有验证码的登陆页面

user用户类

package cn.com.domain;

public class User {
    private int id;
    private String username;
    private String password;
    private String yanzhengma;

    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;
    }

    public String getYanzhengma() {
        return yanzhengma;
    }

    public void setYanzhengma(String yanzhengma) {
        this.yanzhengma = yanzhengma;
    }
}

JDBCUtils工具类
连接数据库

package cn.com.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JDBCUtil {
    //声明连接池对象
    private static DataSource ds;
    //静态代码块加载资源
    static {
        Properties pro = new Properties();
        try {
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //获取连接池对象
            try {
                ds = DruidDataSourceFactory.createDataSource(pro);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //getds
    public static DataSource getDs(){
        return ds;
    }
}

然后根据用户输入信息查找数据库信息

package cn.com.dao;

import cn.com.domain.User;
import cn.com.utils.JDBCUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

public class Userdao {
    //声明获取连接池对象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDs());
    //login
    public User Login(User login){
        try{
            String sql = "select * from user where username = ? and password = ?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), login.getUsername(), login.getPassword());
            return user;
        }catch (DataAccessException e){
            e.printStackTrace();
            return null;
        }
    }
}

下面是验证码图片并将验证码以字符串的形式以session方式共享

package cn.com.web;

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.BufferedReader;
import java.io.IOException;
import java.util.Random;

@WebServlet("/servletImage")
public class ServletImage extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //画个长方型
        int width = 100;
        int height = 50;
        //new出来个图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //画笔对象
        Graphics g = image.getGraphics();
        //填充
        g.setColor(Color.pink);
        g.fillRect(0,0,width,height);
        //画边框
        g.setColor(Color.black);
        g.drawRect(0,0,width-1,height-1);
        //写验证码
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuffer buffer = new StringBuffer();
        Random ran = new Random();
        for (int i = 1; i < 5; i++) {
            int index = ran.nextInt(str.length());
            char ch = str.charAt(index);
            buffer.append(ch);
            g.drawString(ch+"",(width/5)*i,(height/2));
        }
        String s = buffer.toString();
        //Session共享数据
        HttpSession session = request.getSession();
        session.setAttribute("session",s);
        //画干扰线
        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.setColor(Color.green);
            g.drawLine(x1,y1,x2,y2);
        }
        //将图片输出
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

index.jsp首页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录</title>
  </head>
  <style>
    div{
      color: red;
    }
  </style>
  <script>
    window.onload=function () {
      var img = document.getElementById("image");
      img.onclick = function () {
        var date = new Date().getTime()
        img.src = "/day14/servletImage?time=" + date;
      }
    }
  </script>
  <body>
  <form action="/day14/servlet" 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="yanzhengma"></td>
    </tr>
    <tr>
      <td colspan="2"><img id="image" src="/day14/servletImage"></td>
    </tr>
    <tr>
      <td><input type="submit" value="提交"></td>
    </tr>
    </table>
  </form>
  //下面这两行接收的信息来自下面的servlet类
 <div><%=request.getAttribute("error_login") == null ? "" : request.getAttribute("error_login")%></div>
  <div><%=request.getAttribute("error_y") == null ? "" : request.getAttribute("error_y")%></div>

  </body>
</html>

下面重心所在,使用以上所写,判断验证码,判断登录信息

package cn.com.web;

import cn.com.dao.Userdao;
import cn.com.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("/servlet")
public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码,获取参数
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,map);
            String yanzhengma = user.getYanzhengma();
            //获取sesssion中的验证码
            HttpSession session = request.getSession();
            String s = (String) session.getAttribute("session");
            request.removeAttribute("session");
            //判断验证码是否相同
            if (s.equalsIgnoreCase(yanzhengma)){
                //相同则判断用户名
                Userdao userdao = new Userdao();
                User login = userdao.Login(user);
                if (login != null) {
                    //用户名密码正确,跳转到success页面,重定向
                    session.setAttribute("username",user.getUsername());
                    response.sendRedirect(request.getContextPath()+"/success.jsp");
                }else {
                    //失败,储存信息并转发
                    request.setAttribute("error_login","亲,用户名或密码错误");
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
                }
            }else{
                //不相同验证码错误,储存信息并转发
                request.setAttribute("error_y","亲,验证码错误");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

登陆成功,跳转到success页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆成功</title>
</head>
<body>
<h1><%=request.getSession().getAttribute("username")%>,欢迎你哦</h1>
</body>
</html>

你可能感兴趣的:(学习心得)