1.编写login.html登录页面
2.使用Druid数据库连接池技术,操作mysql。
3.使用JdbcTemplate技术封装JDBC
4.登录成功跳转到(请求转发)Success页面,显示:用户名登录成功!
5.登录失败跳转到Fail页面,显示:登录失败,用户名或密码错误
1. 创建项目,写login.html页面,导入相关jar包,导入druid.properties配置文件
(1)html页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<form action="/loginServlet" method="post">
用户名<input type="text" placeholder="输入用户名" name="username"><br>
密码<input type="text" placeholder="输入密码" name="password"><br>
<input type="submit" value="登录">
form>
body>
html>
(2)相关jar包,并把导入的包add as library
(3) 配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbctemplate?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
username=root
password=root
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
2、创建数据库,创建user数据表
CREATE DATABASE jdbctemplate;
USE jdbctemplate;
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);
3、在包com.li.domain下创建User类,与user数据表一一对应。
package com.li.domain;
//用户的实体类
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
4、在包com.li.util下写工具类JDBCUtils
package com.li.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;
//使用Durid连接池
public class JDBCUtils {
private static DataSource ds;
static {
try {
//1、加载配置文件
Properties pro = new Properties();
//使用ClassLoader加载配置文件,获取字节输入流
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(in);
//2、初始化连接池对象
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();
}
}
5、创建包com.li.dao,创建类UserDao,提供login方法
package com.li.dao;
import com.li.domain.User;
import com.li.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
//操作数据库中User表中的类
public class UserDao {
//登陆方法
////声明JDBCTemplate对象共用
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDatasource());
public User login(User loginUser){
try {
//1.编写sql
String sql = "select * from user where username = ? and password = ?";
//2.调用query方法
User user = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());
//第一个参数sql语句,
//第二个参数RowMapper,一般使用BeanPropertyRowMapper实现类,可以完成JavaBean的自动封装
//BeanPropertyRowMapper<类型>(类型.class)
//第三四个参数是填补sql语句的?参数
return user;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package com.li.web.servlet;
import com.li.dao.UserDao;
import com.li.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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@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");
// //封装user对象
User user = new User();
// user.setUsername(username);
// user.setPassword(password);
Map<String, String[]> map = request.getParameterMap();
try {
BeanUtils.populate(user,map);
// BeanUtils.populate可以将map集合的键值对信息,封装到对应的JavaBean对象中
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserDao userDao = new UserDao();
User loginUser = userDao.login(user);
if(loginUser == null){
request.getRequestDispatcher("/failServlet").forward(request,response);
}
else{
//使用Request域对象,在一次请求中共享数据
request.setAttribute("user",loginUser);
request.getRequestDispatcher("/successServlet").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
7、编写登陆失败页面
package com.li.web.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 java.io.IOException;
@WebServlet("/failServlet")
public class failServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登陆失败");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
8、编写登录成功页面
package com.li.web.servlet;
import com.li.domain.User;
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;
@WebServlet( "/successServlet")
public class successServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//输出
User user = (User)request.getAttribute("user");
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(user.getUsername()+"登陆成功");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}