/**个人笔记 */
?1.添加各依赖包
2.Druid配置文件
#驱动加载
driverClassName=com.mysql.cj.jdbc.Driver
#注册驱动
url=jdbc:mysql://localhost:3306/login?characterEncoding=utf-8
#连接数据库的用户名
username=root
#连接数据库的密码
password=123
#属性类型的字符串,通过别名的方式配置扩展插件, 监控统计用的stat 日志用log4j 防御sql注入:wall
filters=stat
#初始化时池中建立的物理连接个数。
initialSize=5
#最大的可活跃的连接池数量
maxActive=300
#获取连接时最大等待时间,单位毫秒,超过连接就会失效。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
maxWait=10000
#连接回收器的运行周期时间,时间到了清理池中空闲的连接,testWhileIdle根据这个判断
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql,要求是一个查询语句。
validationQuery=SELECT 1
#建议配置为true,不影响性能,并且保证安全性。 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis, 执行validationQuery检测连接是否有效。
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。设置为false
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能,设置为false
testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。
poolPreparedStatements=false
#池中能够缓冲的preparedStatements语句数量
maxPoolPreparedStatementPerConnectionSize=200
3.JDBC工具类
package Utils;
import com.alibaba.druid.pool.DruidDataSource;
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 dataSource;
static {
try {
//加载配置文件
Properties properties = new Properties();
//使用ClassLoader加载配置文件,获取字符输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(is);
//初始化连接池对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接池对象
public static DataSource getDataSource() {
return dataSource;
}
//获取Connection对象
public static Connection getConnection () throws SQLException {
return dataSource.getConnection();
}
}
3.dao层
package Dao;
import User.User;
import Utils.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 操作数据库中的loginDemo类
* */
public class UserDao {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* param loginUser 只包含用户名和密码;
* return 包含用户所有数据;
* */
public User loginUser (User userLogin) {
try {
//编写SQL语句
String SQL = "select * from logindemo where username = ? and password = ?";
//查询sql是否符合条件;
User user = template.queryForObject(SQL, new BeanPropertyRowMapper<User>(User.class), userLogin.getUsername(), userLogin.getPassword());
//如果符合则返回查询的信息;
return user;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
//如果没查到会报空指针异常,则返回null;
}
}
4.创建user对象
package User;
/**
* user对象
* */
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 + '\'' +
'}';
}
}
5.制作验证码
package User;
import com.mysql.cj.xdevapi.Session;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;/**/
/**
验证码生成;
*/
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证码的宽;
int width = 100;
//验证码的高;
int height = 50;
//获取图片对象
BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//通过图片对象获取画笔对象
Graphics g = img.getGraphics();
//设置验证码底色画笔颜色
g.setColor(Color.pink);
//设置验证码底色
g.fillRect(0,0,width,height);
//设置验证码边框画笔颜色
g.setColor(Color.blue);
//绘制验证码边框
g.drawRect(0,0 ,width -1,height -1);
//验证码字符集
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz1234567890";
//获取随机方法
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
//绘制4个字符
for (int i = 1; i <= 4 ; i++) {
//设置随机范围
int index = random.nextInt(str.length());
char ch = str.charAt(index);
stringBuilder.append(ch);
g.drawString(ch+"",width/5*i,height/2);
}
//获取session对象
HttpSession session = request.getSession();
//将session对象的内容服务器内共享
session.setAttribute("CheckCode_Session",stringBuilder.toString());
//绘制10条干扰线
for (int i = 1; i <= 1 ; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//图片输出
ImageIO.write(img,"jpeg",response.getOutputStream());
}
}
6.login page servlet
package Servlet;
import Dao.UserDao;
import User.User;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置request的编码
request.setCharacterEncoding("utf-8");
//获取session对象
HttpSession session = request.getSession();
//通过session对象获取验证码代码块共享的验证码
String check_session = (String) session.getAttribute("CheckCode_Session");
//获取验证码后删除这个属性,以保证回退页面后的验证码失效
session.removeAttribute("Check_Session");
//获取表单页面输入的验证码
String checkCode = request.getParameter("CheckCode");
//判断:如果从表单页面获取的验证码非空 并且与验证码代码块发回来的验证码相符则执行
if (check_session != null && check_session.equalsIgnoreCase(checkCode)) {
//将表单信息封装为一个map集合
Map<String, String[]> parameterMap = request.getParameterMap();
//todo 测试用 --->遍历集合
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String key = entry.getKey();
String[] value = entry.getValue();
for (String s1: value) {
System.out.println(key + "----" + s1);
}
}
//新建一个user对象
User user = new User();
try {
//使用javabean将表单内容封装为对象
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//todo 测试用 ---> 检查user对象的内容
System.out.println(user.getId()+"---"+user.getUsername() + "----" + user.getPassword());
//创建dao层对象
UserDao userDao = new UserDao();
//将封装后的对象引入dao层验证表单信息
User user2 = userDao.loginUser(user);
//判断dao层传回来的数据,如果数据不正确会报空指针异常
if (user2 == null ) {
//共享的字符串
String s1 = "账户或密码错误!";
//如果没查到,将该信息在服务器内部转发至登陆页面,达到提示的效果
session.setAttribute("prompt",s1);
//跳转到登陆页面
request.getRequestDispatcher("/Login.jsp").forward(request,response);
//删除页面提示,保证页面整洁
session.removeAttribute("prompt");
//todo 测试用 --->
System.out.println("账户密码错误已接受");
}else {
//todo 测试用 --->
System.out.println("账户正确已接受");
//将用户名转发到成功页面
session.setAttribute("user",user.getUsername());
//跳转到登录成功页面
request.getRequestDispatcher("/successServlet").forward(request,response);
}
}else {
String s2 = "验证码错误!";
//将验证码错误提示转发至登陆页面
session.setAttribute("CheckNull",s2);
//跳转到登陆页面
request.getRequestDispatcher("/Login.jsp").forward(request,response);
//删除提示信息,保证页面整洁
session.removeAttribute("CheckNull");
//todo 测试用--->
System.out.println("验证码错误已接受");
}
}
}
7.success page Servlet
package Servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 登陆成功页面
* 含带用户名的欢迎标语 与 上次的登陆时间
* */
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//调用post方法
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取cookie对象
Cookie[] cookies = request.getCookies();
//设置编码字符集
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取session对象
HttpSession session = request.getSession();
//接受session转发的内容
Object user = session.getAttribute("user");
//是否首次登录的判断
boolean flag = false;
//如果cookie非空
if (cookies != null) {
//遍历获取到的cookie集合
for (Cookie cookie : cookies) {
//获取用户名
String name = cookie.getName();
//判断用户名是否包含上次服务器发送给客户端的时间
if (name.equals("lastTime")) {
//如果有,就将判断关键词转为true
flag = true;
//创建事件对象
Date date = new Date();
//设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = sdf.format(date);
//将时间格式转码为URL编码,防止出现中文乱码bug
String encode = URLEncoder.encode(format,"utf-8");
//将编码后的字符串发送给客户端
cookie.setValue(encode);
//设置cookie的最大存活时间为一个月
cookie.setMaxAge(60 * 60 * 24 * 30);
//发送cookie
response.addCookie(cookie);
//获取cookie信息
String value = cookie.getValue();
//解码cookie
String decode = URLDecoder.decode(value, "utf-8");
//打印欢迎标语
response.getWriter().write("<h1>欢迎回来"+user+",你上次的登陆时间为:" + decode +" </h1>");
}
}
}
//如果cookie为空,和cookie的长度为0,和判断关键词为false;则执行
if (cookies == null || cookies.length == 0 || !flag) {
//写欢迎标语
response.getWriter().write("<h1>"+user+"欢迎首次登录</h1>");
//获取时间对象
Date date = new Date();
//设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = sdf.format(date);
//编码
String encode = URLEncoder.encode(format,"utf-8");
//将编码添加到cookie内
Cookie cookie = new Cookie("lastTime",encode);
//发送编码
response.addCookie(cookie);
}
}
}
8.daoTest
package daoTest;
import Dao.UserDao;
import User.User;
import org.junit.Test;
public class daoTest {
@Test
public void testLogin() {
User user = new User();
user.setUsername("zhangsan");
user.setPassword("123");
System.out.println(user.getUsername() + user.getPassword());
UserDao userDao = new UserDao();
userDao.loginUser(user);
}
}
/**
* @Time: 2021/10/28;
* 第一次调试dao层未添加实参列表
* 第二次调试配置文件没有为数据库连接池添加初始化时池中建立的物理连接个数。与最大的可活跃的连接池数量
* */
9.login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<script>
window.onload = function () {
document.getElementById("cc").onclick = function () {
this.src = "/CheckCodeServlet?time=" + new Date().getTime();
}
}
</script>
</head>
<body>
<form action="/loginServlet">
<table>
<tr>
<td>用户名:<input type="text" name="username" id="user"></td>
</tr>
<tr>
<td>密码:<input type="password" name="password" id="password"></td>
</tr>
<tr>
<td>验证码:<input type="text" name="CheckCode" ></td>
</tr>
<tr><%-- 验证码的图片来源 --%>
<td><img src="/CheckCodeServlet" id="cc"></td>
</tr>
<tr>
<td><input type="submit" name="login" id="login" value="登录"></td>
</tr>
</table>
</form>
<div>
<%=session.getAttribute("prompt") == null ? " ": session.getAttribute("prompt")%>
</div>
<div>
<%=session.getAttribute("CheckNull") == null ? "" : session.getAttribute("CheckNull")%>
</div>
</body>
</html>
|