需求:
- 编写login.html登录页面
- 使用Druid数据库连接池技术,操作mysql数据库中user表
- 使用JdbcTemplate技术封装JDBC
- 登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
- 登录失败跳转到FailServlet展示:登录失败,用户名或密码错误
步骤:
-
编写html页面、配置文件,导入jar包
相关jar包(jar包放在web/WEB-INF/lib下):commons-beanutils-1.8.0.jar//BeanUtils jar包 commons-logging-1.2.jar druid-1.0.9.jar //druid连接池jar包 mysql-connector-java-5.1.37-bin.jar //数据库驱动jar包 mchange-commons-java-0.2.12.jar //以下都是JdbcTemplate相关jar包 spring-beans-5.0.0.RELEASE.jar spring-core-5.0.0.RELEASE.jar spring-jdbc-5.0.0.RELEASE.jar spring-tx-5.0.0.RELEASE.jar
html页面(放在web目录下):login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--action的值为虚拟目录+资源路径-->
<form action="/test/loginServlet" method="post">
用户名:<input type="text" name="username"> <br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
配置文件(放在src下):druid.properties
#注册驱动
driverClassName=com.mysql.jdbc.Driver
#数据库连接的url
url=jdbc:mysql:///mydbone
#用户名和密码
username=root
password=root
#连接池初始化大小
initialSize=5
#连接池最大活动量
maxActive=10
#最大延时
maxWait=3000
-
在domain包下创建User类
package com.fengqi.domain; /** * @Author: NieFengQi * @Date: 2019/7/27 16:46 * @Decription:用户的实体类 */ public class User { private int id; private String username; private String password; public User() { } public User(String username, String password) { this.username = username; this.password = password; } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = 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 + '\'' + '}'; } }
-
在utils包下编写工具类JDBCUtils
package com.fengqi.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; /** * @Author: NieFengQi * @Date: 2019/7/27 16:55 * @Decription:JDBC工具类使用,使用Druid连接池技术 */ public class JDBCUtils { private static DataSource ds; static { try { //加载配置文件 Properties pro = new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //通过Druid连接池工厂对象初始化连接池对象 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(); } }
-
在dao包内创建UserDao,提供login方法
package com.fengqi.dao; import com.fengqi.domain.User; import com.fengqi.util.JDBCUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; /** * @Author: NieFengQi * @Date: 2019/7/27 16:50 * @Decription:操作数据库中user表的类 */ public class UserDao { //声明JdbcTemplate,共用这个对象 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /** * * @param loginUser 只有用户名和密码 * @return user包含User类所有字段,若没有查询到则返回null */ public User login(User loginUser){ try { //编写SQL String sql = "select * from user where username=? and password=?"; //通过template中的方法查询sql并封装为对应对象 User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(),loginUser.getPassword()); return user; } catch (DataAccessException e) { e.printStackTrace(); //出现异常则返回空(没查询到) return null; } } }
-
在servlet包下编写LoginServlet、FailServlet、SuccessServlet
LoginServlet:package com.fengqi.web.servlet; import com.fengqi.dao.UserDao; import com.fengqi.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; /** * @Author: NieFengQi * @Date: 2019/7/28 10:27 * @Decription: */ @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置编码 req.setCharacterEncoding("utf-8"); /*//获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("password"); //把请求参数封装为User对象并调用UserDao的login方法 User user = new UserDao().login(new User(username, password));*/ //获取所有请求参数 Map<String, String[]> parameterMap = req.getParameterMap(); //创建User空对象 User loginUser = new User(); //使用BeanUtils封装User对象 try { BeanUtils.populate(loginUser,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //调用UserDao中的login方法并返回user User user = new UserDao().login(loginUser); //判断返回的user是否为空 if (user != null){ //若不为空则设置共享属性,并转发给SuccessServlet req.setAttribute("user",user); req.getRequestDispatcher("/successServlet").forward(req,resp); }else { //若为空则转发到FailServlet req.getRequestDispatcher("/failServlet").forward(req,resp); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } }
FailServlet:
package com.fengqi.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;
/**
* @Author: NieFengQi
* @Date: 2019/7/28 10:47
* @Decription:
*/
@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("<h1 align='center'>登陆失败,用户名或密码错误!!!</h1>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
SuccessServlet:
package com.fengqi.web.servlet;
import com.fengqi.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;
/**
* @Author: NieFengQi
* @Date: 2019/7/28 10:43
* @Decription:
*/
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应编码
response.setContentType("text/html;charset=utf-8");
//从request域中获取属性
User user = ((User) request.getAttribute("user"));
//响应登陆成功到页面
response.getWriter().write("<h1 align='center'>登陆成功,"+user.getUsername()+"欢迎您!!!</h1>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
拓展:
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对象中