目录
项目需求
开发步骤
1. 创建项目,编写html页面,配置文件,导入jar包
2. 创建数据库环境
3. 创建包domain,创建类User
4. 创建包util,编写工具类JDBCUtils
5. 创建包dao,创建类UserDao,提供login方法
6. 创建包servlet,创建类LoginServlet
7. 编写FailServlet 和 SuccessServlet类
包、类层级结构
1. 创建项目,编写html页面,配置文件,导入jar包
html页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--action路径的写法:虚拟目录+Servlet的资源路径--> <form action="/test_login/loginServlet" method="post"> 用户名:<input type="text" name="username"> <br> 密码:<input type="password" name="password"><br> <input type="submit" value="登录"> </form> </body> </html>注意:虚拟目录不唯一,可在此处查看或自行设置
配置文件:druid.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///userinfo username=root(数据库账号) password=root(数据库密码) initialSize=5 maxActive=10 maxWait=3000导入jar包:注意要加载到此工程或模块下。
链接:https://pan.baidu.com/s/1R6gB5pdxpgCsDdddjzlWSA
提取码:oh01
2. 创建数据库环境
CREATE DATABASE userinfo; USE userinfo; CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) UNIQUE NOT NULL, PASSWORD VARCHAR(32) NOT NULL );添加一条数据:
3. 创建包domain,创建类User
package 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 + '\'' + '}'; } }
4. 创建包util,编写工具类JDBCUtils
package util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; //JDBC连接池 使用Druid连接池 public class JDBCUtils { private static DataSource ds; //静态代码块 static { try { //1.加载配置文件 Properties pro = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //2.初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } //获取连接池对象 public static DataSource getDataSource() { return ds; } //获取连接Connection对象 public static Connection getConnection() throws SQLException { return ds.getConnection(); } }
5. 创建包dao,创建类UserDao,提供login方法
package dao; import domain.User; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import util.JDBCUtils; //操作数据库中User表的类 public class UserDao { //声明JDBCTemplate对象共用 private JdbcTemplate template = 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 = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), loginUser.getUsername(), loginUser.getPassword()); return user; }catch (Exception e){ e.printStackTrace(); //记录日志 return null; } } }
6. 创建包servlet,创建类LoginServlet
package servlet; import dao.UserDao; import 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 { //1.设置编码 req.setCharacterEncoding("utf-8"); /*//2.获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("password"); //3.封装user对象 User loginUser = new User(); loginUser.setUsername(username); loginUser.setPassword(password);*/ //获取所有请求参数 Map<String, String[]> map = req.getParameterMap(); //创建User对象 User loginUser = new User(); //使用BeanUtils封装 try { BeanUtils.populate(loginUser, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //4.调用UserDao的login方法 UserDao dao = new UserDao(); 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); } }
7. 编写FailServlet 和 SuccessServlet类
package 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); } }package servlet; import 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 { //获取request域中共享的user对象 User user = (User) request.getAttribute("user"); if (user != null) { //打印提示信息 //设置页面编码 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); } }
实现效果: