登陆页面(附自动刷新验证码)

最近闲来无事,就用idea写了一个简单的登陆页面,仅供自学java代码的java初学者,以下是我的源码,包括简单的前端代码:

按照MVC,先来javaBean代码

package com.test.bean;

/**
 * 包名:com.test.bean
 * 作者:David
 * 日期:2018/7/16 15:42
 **/


public class Student {
    private int id;
    private String name;
    private String password;
    private String love;

    public Student(int id, String name, String password, String love) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.love = love;
    }

    public Student() {

    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", love='" + love + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLove() {
        return love;
    }

    public void setLove(String love) {
        this.love = love;
    }
}业务层:
package com.test.service;

import com.test.bean.Student;
import com.test.dao.checkDao;

/**
 * 包名:com.test.service
 * 作者:David
 * 日期:2018/7/16 16:21
 **/


public class checkService {
    public Student check(String name, String password, String love) {
        checkDao dao = new checkDao();
        Student student = null;
        try {
            student = dao.check(name,password,love);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return student;
    }
}

dao层:

package com.test.dao;

import com.test.bean.Student;
import com.test.utils.JDBCUtilDruid;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 包名:com.test.dao
 * 作者:David
 * 日期:2018/7/16 16:24
 **/


public class checkDao {
    public Student check(String name, String password, String love) throws Exception {
        JdbcTemplate template = new JdbcTemplate(JDBCUtilDruid.getDataSource());
        String sql = "select * from student where name=? and password=? and love=?";
        Student student = template.queryForObject(sql, new BeanPropertyRowMapper<>(Student.class), name, password, love);
        return student;
    }
}

servlet层:(登陆)

package com.test.web.servlet;

import com.test.bean.Student;
import com.test.service.checkService;

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.io.IOException;

/**
 * 包名:${PACKAGE_NAME}
 * 作者:David
 * 日期:2018/7/16 15:47
 **/


@WebServlet(name = "loginServlet", urlPatterns ="/login")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String love = request.getParameter("love");
        String codeName = request.getParameter("codeName");
        String codeSession = (String) request.getSession().getAttribute("codeSession");
        if (codeName.equalsIgnoreCase( codeSession)){
            checkService service = new checkService();
            Student student = service.check(name,password,love);
            if (student != null){
                request.setAttribute("student",student);
                request.getRequestDispatcher("welcome.jsp").forward(request,response);
            }
            else {
                request.setAttribute("msg","用户信息错误,请从新输入");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
        }
        else {
            request.setAttribute("codeMsg","验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }


    }
}

验证码:

package com.test.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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(urlPatterns = "/codeTest")
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);
      //  生成随机字符
      //  准备数据
      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("codeSession", code);

      //  将画布显示在浏览器中
      ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
   }

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

}

使用过滤器,解决所有请求响应的中文乱码:

package com.test.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 包名:${PACKAGE_NAME}
 * 作者:David
 * 日期:2018/7/16 15:45
 **/


@WebFilter(filterName = "encodeFilter",urlPatterns = "/*")
public class encodeFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

自定义一个druid连接池工具类:

package com.test.utils;

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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 包名:com.itheima.utils
 * 作者:Leevi
 * 日期2018-06-21  17:55
 */
public class JDBCUtilDruid {
    private static DataSource ds;
    static {
        InputStream in = null;
        try {
            Properties properties = new Properties();
            in = JDBCUtilDruid.class.getResourceAsStream("/druidconfig.properties");
            properties.load(in);
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static DataSource getDataSource(){
        return ds;
    }
    public static Connection getConnection() throws SQLException {
        //从Druid连接池中获取连接对象
        return ds.getConnection();
    }
    public static void close(Statement stm, Connection conn) throws SQLException {
        if (stm != null) {
            stm.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
    public static void close(ResultSet rst, Statement stm, Connection conn) throws SQLException {
        if (rst != null) {
            rst.close();
        }
        close(stm,conn);
    }

    public static void main(String[] args) throws SQLException {
        //要使用Druid连接池获取一个连接
        Connection conn = JDBCUtilDruid.getConnection();

        //怎么将conn还到池子中
        conn.close();
    }
}

三个简单的前端页面:首页,登陆,欢迎页面

%--一:
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/7/16
  Time: 15:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    首页
  
  
  

你好,欢迎来到英雄联盟

点击进入登陆页面

二:

%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/7/16
  Time: 15:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登陆页面



用户名
密码
爱好
验证码
点击图片刷新
${msg}
${codeMsg}

三:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    欢迎页面


欢迎${student.name}来到召唤师峡谷

所需所有jar包:

commons-beanutils-1.8.3.jar
commons-logging-1.1.1.jar
druid-1.0.9.jar
javax.servlet.jsp.jstl.jar
jstl-impl.jar
mysql-connector-java-5.1.18-bin.jar
spring-beans-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-jdbc-4.2.4.RELEASE.jar
spring-tx-4.2.4.RELEASE.jar

druid配置文件:

druidconfig.properties

 

 

 

 

 

 

你可能感兴趣的:(登陆页面)