第二章 Servlet生命周期
1.用户登录验证
流程图:
项目目录整体结构:
实现的功能:
控制台页面:
登陆页面:
登录正确:
登录错误:
导包配置:
小丫头爱学习 16:41:43
添加web模块 添加外部模块依赖 运行代码请求,tomcat需要跑起来
小丫头爱学习 16:43:36
idea自动加载tomcat 完成项目发布 以及代码运行
代码部分:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 定义login servlet类-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>
</servlet>
<!-- 定义servlet请求映射-->
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern> <!--请求的地址-->
</servlet-mapping>
</web-app>
LoginServlet:
package com.servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("请求到达了LoginServiet");
System.out.println("uri:"+req.getRequestURI());
System.out.println("url:"+req.getRequestURL());
System.out.println("romote address:"+req.getRemoteHost());
System.out.println("remote ip address:"+req.getRemoteAddr());
System.out.println("remoto port:"+req.getRemotePort());
System.out.println("项目路径:"+req.getContextPath()); //请求的项目路径
//获取客户端传入的参数数据
String userName=req.getParameter("userName");
String password=req.getParameter("password");
if ("admin".equals(userName)&&"123456".equals(password)){
//设置要带到页面的数据
req.setAttribute("userName",userName);
//通过请求对象,获取请求转发器,用于在服务端跳转页面
RequestDispatcher rd=req.getRequestDispatcher("/success.jsp");
//使用转发器完成跳转
rd.forward(req,resp);
}else{
//跳转到失败页面
//客户端重定向 注意:重新定向的时候要带上项目地址
//resp.sendRedirect(req.getContextPath()+"/login.jsp");
//resp.sendRedirect(req.getContextPath()+"/fail.jsp");
//重新跳回登录页面,但是要给用户提示错误信息,此时不需要带项目地址 (判断何时用转发和重定向:需要带数据过去就用转发,否则用重定向)
req.setAttribute("error","用户名或密码错误!");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
}
login.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/7/29
Time: 16:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- request.getContextPath() 获取项目路径--%>
<form action="<%=request.getContextPath()%>/LoginServlet" method="post"> <!--action=“请求路径地址”-->
用户名:<br/>
<input type="text" name="userName"/><br/>
密码:<br/>
<input type="password" name="password"/><br/>
<input type="submit" value="登录"/><br/>
<div style="color:red"><%=request.getAttribute("error")==null?"":request.getAttribute("error")%></div>
</form>
</body>
</html>
success.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/7/29
Time: 17:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>欢迎,<%=request.getAttribute("userName")%>,进去系统后台 </h1>
</body>
</html>
fail.jsp:
Date: 2022/7/29
Time: 17:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>抱歉,登录失败!</h1>
<a href="login.jsp">返回登录页面</a>
</body>
</html>
2.调用数据库实现用户登录验证
DAO分层结构步骤:
0.确定业务功能,图书管理
------------------
1.建库建表: Book
2.创建java项目
3.添加jar包: 数据库jar包,并引用
4.创建util包,创建BaseDAO工具类
5.创建实体包,创建实体类
实体包: entity,
实体类: Book(实体类一般和表名一致)
6.创建数据访问层包/实现包,创建数据访问层接口,创建数据访问层实现类
数据访问层包: dao
数据访问层接口: IBookDAO
数据访问层实现包: impl
数据访问层实现类: BookDAOImpl
7.创建业务层包/实现包,业务层接口,业务层实现类
业务层包: service
业务层层接口: IBookService
业务层实现包: impl
业务层实现类: BookServiceImpl
8.创建程序入口,进行测试
项目目录整体结构:
实现的功能:
数据库和表页面:
控制台页面:
登录页面:
错误登录:
正确登录:
导包配置:
WEB-INF下lib包,添加jar包,支持服务器查询,复制进来
还未和项目关联 ,需要Modules配置一下项目关联,+JARs or Directories…(jar或目录都可)选择jar包或者jar包的上级目录
添加修改的代码部分:
创建数据库:
#创建数据库
create database 70728_db1
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则
创建表:
create table users
(
userId int primary key auto_increment,
userName varchar(20),
password varchar(20)
);
select * from users;
insert into users
(userName,password)
select 'test1','test1' union
select 'test2','test2' ;
select * from users;
BaseDAO:
package com.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseDAO {
//四大金刚
//驱动类
private static final String DRIVER="com.mysql.cj.jdbc.Driver";
//连接地址
private static final String URL="jdbc:mysql://localhost:3306/70728_db1?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
//用户名
private static final String USER="root";
//密码
private static final String PASSWORD="123456";
//获取连接
public static Connection getConnection(){
Connection con = null;
try{
//加载驱动类
Class.forName(DRIVER);
//获取连接
con = DriverManager.getConnection(URL,USER,PASSWORD);
}catch(Exception ex){
ex.printStackTrace();
}
return con;
}
//关闭数据库对象
public static void closeAll(Connection con,Statement st,ResultSet rs){
if(rs!=null){
try{
rs.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(st!=null){
try{
st.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(con!=null){
try{
con.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用设置参数方法
public static void setParams(PreparedStatement pst,Object[] params){
if(params==null){
return;
}
for(int i=0;i<params.length;i++){
try{
pst.setObject(i+1,params[i]);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用增删改
public static int executeUpdate(String sql,Object[] params){
Connection con = null;
PreparedStatement pst = null;
int res = -1;
try{
//获取连接
con = getConnection();
//创建预编译命令执行对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行
res = pst.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,null);
}
return res;
}
//通用查询
public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {
List<Map<String,Object>> rows = new ArrayList<>();
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
//获取连接
con = getConnection();
//获取命令对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行查询
rs = pst.executeQuery();
//通过rs获取结果集的结构信息
ResultSetMetaData rsmd = rs.getMetaData();
//获取结果集的列数
int colCount = rsmd.getColumnCount();
//遍历查询结果,并封装到List<Map>中
while(rs.next()){
//用Map存储当前行的各个列数据
Map<String,Object> map = new HashMap<>();
//循环获取每一列的信息
for(int i=1;i<=colCount;i++){
//获取列名(使用rsmd)
String colName = rsmd.getColumnLabel(i);
//获取列值(使用rs)
Object colVal = rs.getObject(i);
//将当前列存储到map中
map.put(colName,colVal);
}
//将遍历的当前行的数据存储到List中
rows.add(map);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,rs);
}
return rows;
}
}
Users:
package com.entity;
public class Users {
private Integer userId;
private String userName;
private String password;
public Users() {
}
public Users(Integer userId, String userName, String password) {
this.userId = userId;
this.userName = userName;
this.password = password;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
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 "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
IUsersDAO:
package com.dao;
import com.entity.Users;
public interface IUsersDAO {
Users findByUserNameAndPassword(String userName,String password);
}
UsersDAOImpl :
package com.dao.impl;
import com.dao.IUsersDAO;
import com.entity.Users;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class UsersDAOImpl implements IUsersDAO {
@Override
public Users findByUserNameAndPassword(String userName, String password) {
String sql="select userId,userName,password from Users"+
" where userName=? and password=?";
Object[] params={userName,password};
List<Map<String,Object>> rows=BaseDAO.executeQuery(sql,params); //返回的是list列表,需要的是demo对象
if(rows.size()>0){
Map<String,Object> map=rows.get(0);
Users users=new Users(
(Integer) map.get("userId"),
(String) map.get("userName"),
(String) map.get("password")
);
return users;
}
return null;
}
}
IUsersService:
package com.service;
import com.entity.Users;
public interface IUsersService {
Users login(String userName,String password);
}
UsersServiceImpl:
package com.service.impl;
import com.dao.IUsersDAO;
import com.dao.impl.UsersDAOImpl;
import com.entity.Users;
import com.service.IUsersService;
public class UsersServiceImpl implements IUsersService {
IUsersDAO iUsersDAO=new UsersDAOImpl(); //需要调用IUsersDAO的具体实现
@Override
public Users login(String userName, String password) {
return iUsersDAO.findByUserNameAndPassword(userName,password);
}
}
LoginServlet:
package com.servlet;
import com.entity.Users;
import com.service.IUsersService;
import com.service.impl.UsersServiceImpl;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
//创建业务层对象
IUsersService usersService=new UsersServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("请求到达了LoginServiet");
System.out.println("uri:"+req.getRequestURI());
System.out.println("url:"+req.getRequestURL());
System.out.println("romote address:"+req.getRemoteHost());
System.out.println("remote ip address:"+req.getRemoteAddr());
System.out.println("remoto port:"+req.getRemotePort());
System.out.println("项目路径:"+req.getContextPath()); //请求的项目路径
//获取客户端传入的参数数据
//设置请求数据的编码,避免获取数据乱码
req.setCharacterEncoding("utf-8");
String userName=req.getParameter("userName");
String password=req.getParameter("password");
//使用业务层对象查询用户数据
Users users=usersService.login(userName,password);
if(users==null){
//账号或密码不对
req.setAttribute("error","用户名或密码错误!");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}else {
//正确,跳转到成功页面
req.setAttribute("userName",userName);
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
/*
if ("admin".equals(userName)&&"123456".equals(password)){
//设置要带到页面的数据
req.setAttribute("userName",userName);
//通过请求对象,获取请求转发器,用于在服务端跳转页面
RequestDispatcher rd=req.getRequestDispatcher("/success.jsp");
//使用转发器完成跳转
rd.forward(req,resp);
}else{
//跳转到失败页面
//客户端重定向 注意:重新定向的时候要带上项目地址
//resp.sendRedirect(req.getContextPath()+"/login.jsp");
//resp.sendRedirect(req.getContextPath()+"/fail.jsp");
//重新跳回登录页面,但是要给用户提示错误信息,此时不需要带项目地址 (判断何时用转发和重定向:需要带数据过去就用转发,否则用重定向)
req.setAttribute("error","用户名或密码错误!");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
*/
}
}
…待补充!
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';