使用jsp+session实现一个登录界面
1.1.1.1案例需求描述
提供登录页面,用于用户登录(用户名和密码需要查询数据库)。如果登录失败,需要回到登录页面(给出提示信息)。如果登录成功,页面进行跳转,在成功页面上显示登录成功的总人数。
1.1.1.2案例流程分析
1.1.1.3案例准备 -创建数据库
1.1.1创建数据库
1.1.1.3建表语句
create database web02_login;
use web02_login;
create table user(
uid int primary key auto_increment,
username varchar(20),
password varchar(20),
nickname varchar(20)
);
insert into user values (null,'zs','123','张三');
insert into user values (null,'ls','123','李四');
insert into user values (null,'ww','123','王五');
1.1.1.4导入相关jar包
其导入的包为数据库连接池-druid和数据库连接驱动
项目包结构
1.1.1.5login.jsp
jsp的运行原理
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% /** * 判断request域中是否有错误信息:(第一次进入登录页面的时候,没有错误信息) * * 如果有错误信息:显示错误信息 */ String msg = ""; if(request.getAttribute("msg") != null){ // 有错误信息:显示错误信息: msg = (String)request.getAttribute("msg"); } %> <h1>登录界面</h1> <h3><font color="red"><%=msg%></font></h3> <form action="/WEB04_login/LoginServlet" method="post"> <table border="1" width="600"> <tr> <td>用户名</td> <td><input type="text" name="username"/></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password"/></td> </tr> <tr> <td colspan="2"><input type="submit" value="登录"></td> </tr> </table> </form> </body> </html>
1.1.1.6登录成功的界面-success.jsp
<%@page import="domain.User"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% //进行判断用户是否通过登录界面 if(request.getSession().getAttribute("existUser") == null){ %> <!-- 当需要添加html标签时需要进行隔开 --> <h1>你好,你还没有登录,请点击链接进行登录<a href="/WEB04_login/login.jsp">登录</a></h1> <% }else{ %> <h1>用户登陆成功</h1> <% User user = (User)request.getSession().getAttribute("existUser"); int count = (int)request.getServletContext().getAttribute("count"); %> <h3>你好:<%= user.getUsername()%></h3> <h3>总的登陆成功的人数<%= count %></h3> <% } %> </body> </html>
1.1.1.7控制层(controller)
1.InitServlet.java
package controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** *初始化的servlet *将这个Servlet配置成启动时加载 */ public class InitServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override /** * 初始化的方法: */ public void init() throws ServletException { // 初始一个值为0。 int count = 0; // 将这个值存入到ServletContext域中。 this.getServletContext().setAttribute("count", count); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
这里需要注意的是需要对这个servlet在web.xml中进行配置
通过<load-on-startup>标签中进行配置,标签中填入一个大于2的整形数字(因为tomcat服务器中有一个servlet默认的优先级为1),其数字越小,在服务器启动加载的优先级越高!
2.LoginServlet.java
package controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import model.UserModel; import domain.User; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 接收数据 // 处理中文乱码 request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username+password); // 封装数据 User user = new User(); user.setUsername(username); user.setPassword(password); User login = UserModel.Login(username, password); // 处理数据 if (login == null) { // 登录失败 // 向request域中保存一个数据 request.setAttribute("msg", "用户名或密码错误"); // 使用请求转发进行页面跳转 request.getRequestDispatcher("login.jsp").forward(request, response); } else { // 登录成功 //保存用户信息 HttpSession session = request.getSession(); session.setAttribute("existUser",login); // 记录登录成功的人数: // 将ServletContext中的值取出 +1 int count = (int) this.getServletContext() .getAttribute("count"); // 进行了+1的操作 count++; // 将+1后的值存回到ServletContext中去。 this.getServletContext().setAttribute("count", count); // 重定向到成功页面 response.sendRedirect("/WEB04_login/success.jsp"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
接受数据类-User.java
package domain; /** * @author ztr * @version 创建时间:2021年4月16日 上午11:00:32 * 类说明 */ public class User { private Integer uid; private String username; private String password; public User(Integer uid, String username, String password) { super(); this.uid = uid; this.username = username; this.password = password; } public User() { super(); // TODO Auto-generated constructor stub } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } 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; } }
数据处理类-UserModel.java
package model; import java.sql.Connection; import domain.User; import utils.*; /** * @author ztr * @version 创建时间:2021年4月16日 上午11:02:13 类说明 */ public class UserModel { public static User Login(String username, String password) throws Exception { Connection connection = JdbcUtils.GetConnection(); String sql = "select username,password from user where username = ? and password = ?"; User user = BaseDao.GetInstance(connection, User.class, sql, username, password); return user; } }
数据库连接工具类
JdbcUtils.java
package utils; import java.io.InputStream; import java.util.Properties; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; /** * @author ztr * @version 创建时间:2021年3月29日 上午10:20:16 类说明 */ /* * 获取连接 * * @return Connection */ public class JdbcUtils { public JdbcUtils() { super(); // TODO Auto-generated constructor stub } private static DataSource source; static { try { Properties pro = new Properties(); InputStream is = JdbcUtils.class.getClassLoader() .getResourceAsStream("druid.properties"); pro.load(is); source = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection GetConnection() throws Exception { Connection connection = source.getConnection(); return connection; } /* * 关闭资源 */ public static void closeResource(Connection connection, PreparedStatement ps) { try { if (ps != null) ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 关闭资源 */ public static void closeResource1(Connection connection, PreparedStatement ps, ResultSet rs) { try { if (ps != null) ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (rs != null) rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
BaseDao.java
package utils; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.List; /** * @author ztr * @version 创建时间:2021年4月16日 上午11:21:09 类说明 */ public class BaseDao { // 通用的增删改操作 public static void update(Connection connection, String sql, Object... args) { // 获取数据连接 // 预编译sql语句返回preparedStatement PreparedStatement prepareStatement = null; try { prepareStatement = connection.prepareStatement(sql); // 填充占位符 // prepareStatement.setObject的下标从1开始 for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } // 执行 prepareStatement.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 资源的关闭 JdbcUtils.closeResource(null, prepareStatement); } } /** * 返回一个数据 * * @param clazz * @param sql * @param args * @return */ public static <T> T GetInstance(Connection connection, Class<T> clazz, String sql, Object... args) { PreparedStatement prepareStatement = null; // 获取结果集 ResultSet resultSet = null; try { prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 获取元数据 ResultSetMetaData metaData = resultSet.getMetaData(); // 通过metaData获取结果集中的列数 int columnCount = metaData.getColumnCount(); if (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // 获取列值 Object columnValue = resultSet.getObject(i + 1); // 获取每列的列名 String columnName = metaData.getColumnLabel(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考虑该属性是否为私有 field.setAccessible(true); field.set(newInstance, columnValue); } return newInstance; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 关闭资源 JdbcUtils.closeResource1(null, prepareStatement, resultSet); } return null; } /** * 返回多条数据 * @param connection * @param clazz * @param sql * @param args * @return */ public static <T> List<T> getList(Connection connection, Class<T> clazz, String sql, Object... args) { PreparedStatement prepareStatement = null; // 获取结果集 ResultSet resultSet = null; try { prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 获取元数据 ResultSetMetaData metaData = resultSet.getMetaData(); // 通过metaData获取结果集中的列数 int columnCount = metaData.getColumnCount(); // 创建集合对象 ArrayList<T> list = new ArrayList<T>(); while (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // 获取列值 Object columnValue = resultSet.getObject(i + 1); // 获取每列的列名 String columnName = metaData.getColumnLabel(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考虑该属性是否为私有 field.setAccessible(true); field.set(newInstance, columnValue); } list.add(newInstance); } return list; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 关闭资源 JdbcUtils.closeResource1(null, prepareStatement, resultSet); } return null; } }
数据库连接池配置文件-druid.properties
url=jdbc:mysql://localhost:3306/web02_login
username=root
password=XXX
driverClassName=com.mysql.cj.jdbc.Driver
运行结果
登录界面
用户名或者密码错误
登陆成功
以上博文只是记录学习,若有错误之处,还请大家谅解。