黑马程序员IDEA版JAVA基础班\JavaWeb部分视频\2-10Request和Response\第5节 request登录案例
用户登录案例需求:
1.编写login.html登录页面
username & password 两个输入框
2.使用Druid数据库连接池技术,操作mysql,day14数据库中user表
3.使用JdbcTemplate技术封装JDBC
4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误登录案例分析:
1. 创建项目,导入html页面,配置文件,jar包
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form action="" method="post"> 9 用户名:<input type="text" name="username"> <br> 10 密码:<input type="password" name="password"><br> 11 12 <input type="submit" value="登录"> 13 14 </form> 15 </body> 16 </html>
把login.html复制到web文件夹中。
把druid的配置文件复制到src文件夹中。
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/day14?characterEncoding=UTF-8&serverTimezone=GMT%2B8 username=root password=root initialSize=5 maxActive=10 maxWait=3000 minIdle=1
项目依赖的.jar包文件放在lib文件夹中,全部一起复制到新建的WEB-INF文件里。
【单元测试】JUnit-4.12使用报java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing错误
所以现在有两个办法解决: 1.junit版本降到4.10 2.导入hamcrest-core-1.3.jar
2. 创建数据库环境
MySQL本地已经安装配置好8.0.17版本,图形化操作软件使用Navicat12。
CREATE DATABASE day14; USE day14; CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) UNIQUE NOT NULL, PASSWORD VARCHAR(32) NOT NULL );
3. 创建包cn.itcast.domain,创建类User
4. 创建包cn.itcast.util,编写工具类JDBCUtils
1 package cn.itcast.util; 2 3 import com.alibaba.druid.pool.DruidDataSourceFactory; 4 5 import javax.sql.DataSource; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.sql.Connection; 9 import java.sql.SQLException; 10 import java.util.Properties; 11 12 13 /** 14 * JDBC工具类 使用Durid连接池 15 */ 16 public class JDBCUtils { 17 18 private static DataSource ds ; 19 20 static { 21 22 try { 23 //1.加载配置文件 24 Properties pro = new Properties(); 25 //使用ClassLoader加载配置文件,获取字节输入流 26 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); 27 pro.load(is); 28 29 //2.初始化连接池对象 30 ds = DruidDataSourceFactory.createDataSource(pro); 31 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 } 38 39 /** 40 * 获取连接池对象 41 */ 42 public static DataSource getDataSource(){ 43 return ds; 44 } 45 46 47 /** 48 * 获取连接Connection对象 49 */ 50 public static Connection getConnection() throws SQLException { 51 return ds.getConnection(); 52 } 53 }
5. 创建包cn.itcast.dao,创建类UserDao,提供login方法
1 package cn.itcast.dao; 2 3 import cn.itcast.domian.User; 4 import cn.itcast.util.JDBCUtils; 5 import org.springframework.dao.DataAccessException; 6 import org.springframework.jdbc.core.BeanPropertyRowMapper; 7 import org.springframework.jdbc.core.JdbcTemplate; 8 9 /** 10 * 操作数据库中User表的类 11 */ 12 public class UserDao { 13 14 //声明JDBCTemplate对象共用 15 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); 16 17 /** 18 * 登录方法 19 * @param loginUser 只有用户名和密码 20 * @return user包含用户全部数据,没有查询到,返回null 21 */ 22 public User login(User loginUser){ 23 try { 24 //1.编写sql 25 String sql = "select * from user where username = ? and password = ?"; 26 //2.调用query方法 27 User user = template.queryForObject(sql, 28 new BeanPropertyRowMapper<User>(User.class), 29 loginUser.getUsername(), loginUser.getPassword()); 30 31 32 return user; 33 } catch (DataAccessException e) { 34 e.printStackTrace();//记录日志 35 return null; 36 } 37 } 38 }编写测试类,检测数据库连接池的响应。
1 package cn.itcast.test; 2 3 import cn.itcast.dao.UserDao; 4 import cn.itcast.domian.User; 5 import org.junit.Test; 6 7 public class UserDaoTest { 8 9 10 11 @Test 12 public void testLogin(){ 13 User loginuser = new User(); 14 loginuser.setUsername("superbaby"); 15 loginuser.setPassword("123"); 16 17 18 UserDao dao = new UserDao(); 19 User user = dao.login(loginuser); 20 21 System.out.println(user); 22 } 23 }
6. 编写cn.itcast.web.servlet.LoginServlet类
.html文件中<form>标签的action=" "
FailServlet
1 package cn.itcast.web.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 @WebServlet("/failServlet") 11 public class FailServlet extends HttpServlet { 12 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 //给页面写一句话 14 15 //设置编码 16 response.setContentType("text/html;charset=utf-8"); 17 //输出 18 response.getWriter().write("登录失败,用户名或密码错误"); 19 20 } 21 22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 23 this.doPost(request,response); 24 } 25 }
SuccessServlet
1 package cn.itcast.web.servlet; 2 3 import cn.itcast.domian.User; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import java.io.IOException; 11 12 @WebServlet("/successServlet") 13 public class SuccessServlet extends HttpServlet { 14 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 15 //获取request域中共享的user对象 16 User user = (User) request.getAttribute("user"); 17 18 if(user != null){ 19 //给页面写一句话 20 21 //设置编码 22 response.setContentType("text/html;charset=utf-8"); 23 //输出 24 response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您"); 25 } 26 27 28 } 29 30 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 this.doPost(request,response); 32 } 33 }
LoginServlet
1 package cn.itcast.web.servlet; 2 3 import cn.itcast.dao.UserDao; 4 import cn.itcast.domian.User; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 @WebServlet("/loginServlet") 14 public class LoginServlet extends HttpServlet { 15 16 @Override 17 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 18 19 this.doGet(request,response); 20 } 21 @Override 22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 23 //1.设置编码 24 request.setCharacterEncoding("utf-8"); 25 //2.获取请求参数 26 String username = request.getParameter("username"); 27 String password = request.getParameter("password"); 28 //3.封装user对象 29 User loginUser = new User(); 30 loginUser.setUsername(username); 31 loginUser.setPassword(password); 32 //4.调用UserDao的login方法 33 UserDao dao = new UserDao(); 34 User user =dao.login(loginUser); 35 36 //5.判断user 37 if (user == null){ 38 //登陆失败 39 request.getRequestDispatcher("/failServlet").forward(request,response); 40 }else{ 41 //登陆成功 42 //存储数据 43 request.setAttribute("user",user); 44 //转发 45 request.getRequestDispatcher("/successServlet").forward(request,response); 46 } 47 } 48 }
23_登录案例_BeanUtils基本使用
commons-beanutils-1.8.0
// LoginServlet
1 package cn.itcast.web.servlet; 2 3 import cn.itcast.dao.UserDao; 4 import cn.itcast.domain.User; 5 import org.apache.commons.beanutils.BeanUtils; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import java.io.IOException; 13 import java.lang.reflect.InvocationTargetException; 14 import java.util.Map; 15 16 17 @WebServlet("/loginServlet") 18 public class LoginServlet extends HttpServlet { 19 20 21 @Override 22 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 23 //1.设置编码 24 req.setCharacterEncoding("utf-8"); 25 /* //2.获取请求参数 26 String username = req.getParameter("username"); 27 String password = req.getParameter("password"); 28 //3.封装user对象 29 User loginUser = new User(); 30 loginUser.setUsername(username); 31 loginUser.setPassword(password);*/ 32 //2.获取所有请求参数 33 Map<String, String[]> map = req.getParameterMap(); 34 //3.创建User对象 35 User loginUser = new User(); 36 //3.2使用BeanUtils封装 37 try { 38 BeanUtils.populate(loginUser,map); 39 } catch (IllegalAccessException e) { 40 e.printStackTrace(); 41 } catch (InvocationTargetException e) { 42 e.printStackTrace(); 43 } 44 45 46 //4.调用UserDao的login方法 47 UserDao dao = new UserDao(); 48 User user = dao.login(loginUser); 49 50 //5.判断user 51 if(user == null){ 52 //登录失败 53 req.getRequestDispatcher("/failServlet").forward(req,resp); 54 }else{ 55 //登录成功 56 //存储数据 57 req.setAttribute("user",user); 58 //转发 59 req.getRequestDispatcher("/successServlet").forward(req,resp); 60 } 61 62 } 63 64 @Override 65 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 66 this.doGet(req,resp); 67 } 68 }
9. BeanUtils工具类,简化数据封装
* 用于封装JavaBean的
1. JavaBean:标准的Java类
1. 要求:
1. 类必须被public修饰
2. 必须提供空参的构造器
3. 成员变量必须使用private修饰
4. 提供公共setter和getter方法
2. 功能:封装数据
2. 概念:
成员变量:
属性:setter和getter方法截取后的产物
例如:getUsername() --> Username--> username
3. 方法:
1. setProperty()
2. getProperty()
3. populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中
okey