Java实战之实现用户登录
一、前言
二、案例需求
1.编写login.html登录页面,username&password两个输入框
2.使用Druid数据库连接池技术,操作mysql,day14数据库中的user表
3.使用jdbcTemplate技术封装JDBC
4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎你
5.登录失败跳转到FailServlet展示:登录失败密码错误
三、开始第一步
首先创建项目,写html页面,配置文件,jar包
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/day14/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.cj.jdbc.Driver url=jdbc:mysql:///day14 username=root password=root #初始化连接数量 initialSize=5 #最大连接数 maxActive=10 #最大等待时间 maxWait=3000 filters=stat timeBetweenEvictionRunsMillis=60000 minEvictableIdleTimeMillis=300000 validationQuery=SELECT 1 testWhileIdle=true testOnBorrow=false testOnReturn=false poolPreparedStatements=false maxPoolPreparedStatementPerConnectionSize=200
导入jar包:
四、第二步
创建user类:
package com.wzc.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 + '\'' + '}'; } }
五、第三步
创建jdbcUtils工具类
package com.wzc.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工具类 使用Druid连接池 public class JDBCUtils { private static DataSource ds ; static { try { // 加载配置文件 Properties pro = new Properties(); // 使用ClassLoader加载配置文件,获取字节输入流 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; } /*获取连接connection对象*/ public static Connection getConnection() throws SQLException { return ds.getConnection(); } }
创建UserDao类,提供login方法:
package com.wzc.dao; import com.wzc.domain.User; import com.wzc.util.JDBCUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; //操作数据库中user表的类 public class UserDao { // 声明JDBCTemplate对象共用 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /** * 登录方法 * @param loginUser 只有用户名和密码 * @return user包含用户全部数据,没有查询到则返回null */ public User login(User loginUser){ try{ // 编写sql String sql = "select * from user where username = ? and password = ?"; // 调用query方法 User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword()); return user; } catch (DataAccessException e){ e.printStackTrace(); // 记录日志 return null; } } }
编写loginServlet类:
package com.wzc.web.servlet; import com.wzc.dao.UserDao; import com.wzc.domain.User; import org.apache.commons.beanutils.BeanUtils; import javax.servlet.ServletContext; 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"); /*// 获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("password"); // 封装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(); } // 调用UserDao的login方法 UserDao dao = new UserDao(); User user = dao.login(loginUser); // 判断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); } }
六、第四步
编写SuccessServlet类:
package com.wzc.web.servlet; import com.wzc.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(name = "/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); } }
编写FailServelt类
package com.wzc.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 { 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); } }
输入错误的账号和密码
登录失败提示:
七、总结
login.html中form表单的action路径写法:虚拟路径+Servlet的资源路径
**BeanUtils工具类,简化数据封装:**用于封装javaBean
javaBean:标准的java类 功能:封装数据
有一下四点要求:
1.类必须被public修饰
2.必须提供空参的构造器
3.成员变量必须使用private修饰
4.提供公共setter和getter方法
属性:setter和getter方法截取后的产物
例如:getUsername()–>Username–>username
可见username就是属性
方法有三种:
1.setProperty()
2.getProperty()
3.populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中(最常用)
package com.wzc.test; import com.wzc.domain.User; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; import java.lang.reflect.InvocationTargetException; public class BeanUtilsTest { @Test public void test(){ User user = new User(); try { BeanUtils.setProperty(user,"hehe","male"); System.out.println(user); String gender = BeanUtils.getProperty(user, "hehe"); System.out.println(gender); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
到此这篇关于Java实战之实现用户登录的文章就介绍到这了,更多相关Java实现用户登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!