1.工具:IDEA,要用到的包,mysql数据库
1.2数据库
1.3.准备连接数据库的封装方法
package com.qf.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class DbUtils {
private static DruidDataSource druidDataSource;
static {
InputStream is = DbUtils.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties =new Properties();
try {
properties.load(is);
is.close();
druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
}catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn =null;
try{
conn = druidDataSource.getConnection();
}catch (Exception ex) {
ex.printStackTrace();
}
return conn;
}
public static void colse(ResultSet rs, Statement statement, Connection conn) {
try{
if(null != rs) {
rs.close();
}
if(null != statement) {
statement.close();
}
if(null != conn) {
conn.close();
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
2.编写实体类User
public class User {
private Integer id;
private String username;
private String realname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
}
3.编写实体类People
public class People {
private Integer id;
private String name;
private String gender;
private String email;
private Date birthday;
private Timestamp createTime;
private Timestamp updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
}
3.编写druid.properties配置文件,用于数据库的连接
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/servlet?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username=root
password=****
#初始化的时候,连接池中放多少个连接
initialSize=10
# 最大存货的连接数量
maxActive=50
#最小空闲数量
minIdle=5
#配置获取连接等待超时的时间
maxWait=10000
#验证连接池中的连接是否有效的sql语句
validationQuery='select 1'
#在获取连接的时候,验证拿到连接是否为有效连接
testOnBorrow=false
#在归还连接的时候,验证是否为有效连接
test-on-return=false
#空闲的时候验证是否有效
test-while-idle=true
4.准备前端用户登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
用户登录
${param.code == 'error' ? '用户名或者密码错误' : ''}
5.编写UserDao接口
public interface UserDao{
//查寻一个用户
User checkUser(String username, String password);
}
6.编写UserDao接口实现类
package com.qf.dao.impl;
import com.qf.dao.UserDao;
import com.qf.info.People;
import com.qf.info.User;
import com.qf.utils.DataUtils;
import com.qf.utils.DbUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UserDaoImplimplements UserDao{
@Override
public User checkUser(String username, String password) {
User user =null;
Connection conn = DbUtils.getConnection();
String sql ="select id, username, realname from user where username = ? and password = ?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,username);
ps.setObject(2,password);
ResultSet rs = ps.executeQuery();
if (rs.next()){
user =new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getNString("username"));
user.setRealname(rs.getString("realname"));
}
DbUtils.colse(rs,ps,conn);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
7.编写UserService接口
package com.qf.service;
import com.qf.domain.User;
public interface UserService {
//比较用户的用户名和密码
User checkUser(String username, String password);
}
8.编写UserService接口实现类
package com.qf.service.impl;
import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.domain.User;
import com.qf.service.UserService;
public class UserServiceImplimplements UserService {
private UserDao userDao =new UserDaoImpl();
@Override
public User checkUser(String username, String password) {
return userDao.checkUser(username, password);
}
}
9.编写LoginServlet
package com.qf.servlet;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
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(value ="/login", name ="LoginServlet")
public class LoginServletextends HttpServlet {
// ctrl + shift + 左右键
private UserService userService =new UserServiceImpl();
/**
* 在数据库密码存储上会采取一定加密机制。md5(不可逆). 了解:加盐。
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
/**
* 将密码做md5运算之后的字符串。
* 例如:1 -> c4ca4238a0b923820dcc509a6f75849b, 然后再数据库中去比较密文
*/
String md5Pwd = DigestUtils.md5Hex(password);
User user = userService.checkUser(username, md5Pwd);
/**
* 1.当用户为空,表示用户名和密码错误,然后要回到登录页面。
* 2. 要给用户一个提示信息: "用户名或密码错误".
* 3. 要重定向到登录页面.
*/
if(null == user) {
// 如果通过请求转发到登录页面的时候,用户一直刷新,会一直拿着错误的用户名/密码在校验。
resp.sendRedirect("login.jsp?code=error");
}else {
/**
* 正确的处理流程:
* 1.设置到session中。
* 2.到首页,重定向到 /people 对应的Servlet.
*/
HttpSession session = req.getSession();
session.setAttribute("user", user);
/**
* 为什么需要重定向到 PeopleServlet, 从后台携带参数到主页。
*/
resp.sendRedirect("people");
}
}
}