1.编写login.html登录页面 (username & password 两个输入框);
2.使用 Druid 数据库连接池技术,操作mysql;
3.使用 JdbcTemplate 技术封装 JDBC;
4.登录成功跳转到 SuccessServlet 展示:登录成功!用户名,欢迎您;
5.登录失败跳转到 FailServlet 展示:登录失败,用户名或密码错误。
注意:action中的路径为 /虚拟目录/servlet资源路径
.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
CREATE DATABASE userlogin;
USE userlogin;
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);
domain
,创建一个实体类User,实体类User 对应 user 表,该对象对应表中记录。package com.qgl.domain;
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 + '\'' +
'}';
}
}
util
,创建数据库连接池对象和连接对象的工具类 JDBCUtils。注意:durid配置文件中的 数据库路径:url=jdbc:mysql://localhost:3306/userlogin 或 url=jdbc:mysql:///userlogin。
package com.qgl.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;
public class JDBCUtils {
private static DataSource ds;
static{
try {
// 1、加载配置文件
Properties pro = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
// 创建数据库连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接池对象
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 获取连接对象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
dao
,创建操作数据库的 UserDao 接口及 子包 impl
下的 UserDaoImpl 实现类。package com.qgl.dao;
import com.qgl.domain.User;
public interface UserDao {
/**
* 操作数据库的方法
* @param loginUser
* @return
*/
public User login(User loginUser);
}
package com.qgl.dao.impl;
import com.qgl.dao.UserDao;
import com.qgl.domain.User;
import com.qgl.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDaoImpl implements UserDao {
// 声明JDBCTemplate对象公用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 操作数据库的方法,参数为封装为User的用户输入数据,
* 找到返回数据库中的User对象,否则返回null。
* @param loginUser
* @return
*/
@Override
public User login(User loginUser) {
try {
String sql = "select * from user where username = ? and password = ?";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());
return user;
} catch (DataAccessException e) {
return null;
}
}
}
web.servlet
,创建处理登录数据的 loginServelt 类,登录成功后跳转的 successServlet 类,登录失败后跳转的 failServlet 类。package com.qgl.web.servlet;
import com.qgl.dao.UserDao;
import com.qgl.dao.impl.UserDaoImpl;
import com.qgl.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("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置编码
req.setCharacterEncoding("utf-8");
// 获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//3.封装登录用户输入信息为user对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
//4.调用UserDao的login方法,返回数据库中找到的对应user对象
UserDao dao = new UserDaoImpl();
User user = dao.login(loginUser);
//5.判断user
if(user == null){
//登录失败
req.getRequestDispatcher("/failServlet").forward(req,resp);
}else{
//登录成功
//存储数据
req.setAttribute("user",user);
//转发
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
package com.qgl.web.servlet;
import com.qgl.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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取request域中共享的user对象
User user = (User) req.getAttribute("user");
if(user != null){
//设置编码
resp.setContentType("text/html;charset=utf-8");
//输出
resp.getWriter().write("登录成功!"+ user.getUsername() +",欢迎您");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.qgl.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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码
resp.setContentType("text/html;charset=utf-8");
//输出
resp.getWriter().write("登录失败,用户名或密码错误");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
BeanUtils 官网
对于实体类,当属性比较少或者实体类比较少时,可以按照上述 LoginServlet 中对请求的用户输入参数单独设置,封装为实体类对象。但是当属性较多,这样封装起来很麻烦,所以这里使用一个工具类 BeanUtils 工具类来帮我们完成封装。
BeanUtils 工具类,简化数据封装,用于将数据封装为 JavaBean 对象的功能。
JavaBean:标准的Java类,用来封装对象。
JavaBean类的要求:
- 类必须被public修饰;
- 必须提供空参的构造器;
- 成员变量必须使用private修饰;
- 提供公共setter和getter方法。
属性与成员变量的概念区别:
属性:setter 和 getter 方法去掉setter或getter后剩下的名称即为属性。
例如:getUsername() --> Username–>username
使用步骤:
1、导入相关的 jar 包;
2、使用 BeanUtils 工具类中的 populate() 方法。该方法是将 map 集合的键值对信息封装到对应的 JavaBean 对象中。
使用 BeanUtils 工具类封装对象的 LoginServlet 类。
package com.qgl.web.servlet;
import com.qgl.dao.UserDao;
import com.qgl.dao.impl.UserDaoImpl;
import com.qgl.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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置编码
req.setCharacterEncoding("utf-8");
// 获取请求参数
Map<String, String[]> pm = req.getParameterMap();
User loginUser = new User();
try {
//3.封装user对象
BeanUtils.populate(loginUser,pm);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//4.调用UserDao的login方法
UserDao dao = new UserDaoImpl();
User user = dao.login(loginUser);
//5.判断user
if(user == null){
//登录失败
req.getRequestDispatcher("/failServlet").forward(req,resp);
}else{
//登录成功
//存储数据
req.setAttribute("user",user);
//转发
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}