## 案例:用户登录
准备工作:
准备Maven 配置pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>Login</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>Login Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java --> <dependency> <groupId>com.mchange</groupId> <artifactId>mchange-commons-java</artifactId> <version>0.2.12</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.0</version> </dependency> </dependencies> <build> <finalName>Login</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
User实体类:
package com.ftj.domain; /** * 用户实体类javaBean */ public class User { private int id; private String username; private String password; private String gender; public User() { } public User(int id, String username, String password, String gender) { this.id = id; this.username = username; this.password = password; this.gender = gender; } 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; } public String getHehe() { return gender; } public void setHehe(String gender) { this.gender = gender; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", gender='" + gender + '\'' + '}'; } }
UserDao
package com.ftj.dao; /** * 操作数据中,user表的类 */ import com.ftj.domain.User; import com.ftj.util.JDBCUtil; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; public class UserDao { //声明JDBCTemplate对象共用 private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource()); /** * 登录方法 * * @param loginUser 只有用户名和密码 * @return 包含用户全部数据 */ 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>(User.class), loginUser.getUsername(), loginUser.getPassword()); return user; } catch (Exception e) { e.printStackTrace();//记录日志 return null; } } }
登录验证
package com.ftj.servlet; import com.ftj.dao.UserDao; import com.ftj.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; /** * JavaBean:标准的Java类 * 1、要求: * 1、类必须被public修饰 * 2、必须提供空参的构造器 * 3、成员变量必须使用private修饰 * 4、提供公共setter和getter方法 * 2、功能:封装数据 * * 概念: * 成员变量: * 属性:setter和getter方法截取后的产物 * 例如:getUsername()-->Username-->username * * 方法: * 1、setProperty() * 2、getProperty() * 3、populate() */ @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); //4、调用UserDao的login方法*/ Map<String, String[]> map = req.getParameterMap(); User loginUser = new User(); try { BeanUtils.populate(loginUser,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } 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); } }
Druid方式的JDBC
package com.ftj.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; /** * JDBC工具类,使用Durid连接池 */ public class JDBCUtil { private static DataSource ds; static { try { //1、加载配置文件 Properties pro = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 String path = "jdbc.properties"; InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream(path); pro.load(is); //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(); } }
Druid配置文件
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/ftj?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false username=root password=password # 初始化连接数 initialSize=5 #最大连接数 maxActive=10 #超时时间 maxWait=3000 #报错信息意思是说:校验没有设置,将testWhileIdle修改为false不再报错,工程正常运行。 validationQuery:SELECT 1 testWhileIdle:true testOnBorrow:false testOnReturn:false
登录界面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/loginServlet" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> <input type="submit" value="登录"> </form> </body> </html>
JavaBean测试类
package com.ftj.test; import com.ftj.domain.User; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; import java.lang.reflect.InvocationTargetException; public class BeanUtilTest { @Test public void test(){ User user = new User(); try { //BeanUtils.setProperty(user, "username", "ftj"); BeanUtils.setProperty(user,"hehe","male"); //操作的不是成员变量 String hehe = BeanUtils.getProperty(user, "hehe"); System.out.println(hehe); } catch (IllegalAccessException | NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println(user); } }
Druid测试类
package com.ftj.test; import com.ftj.dao.UserDao; import com.ftj.domain.User; import org.junit.Test; public class UserDaoTest { @Test public void testLogin(){ User loginuser = new User(); loginuser.setUsername("superbaby"); loginuser.setPassword("123"); UserDao dao = new UserDao(); User user = dao.login(loginuser); System.out.println(user); } }
That which doesn't kill me makes me stronger!