Servlet对象的生命周期
Servlet对象的生命周期是由Tomcat服务器(中间件)全权负责的。
Tomcat服务器(中间件)有通常被称为WEB容器。
我们自己new的Servlet对象是不受Tomcat管理
WEB容器创建的Servlet对象,这些对象都会被放到一个集合当中HashMap,只有放到HashMap集合当中的Servlet才能够被WEB容器管理
WEB容器底层有HashMap这样的集合
Tomcat启动是会解析web.xml文件,启动的时候Servlet对象并不会被实例化。用户发送请求访问时会创建Servlet对象。
web.xml配置文件:描述请求路径和与Servlet类之间的对应关系。
<!-- <load-on-startup>该标签使对象在web容器启动时,创建Servlet对象
数字表示的是该对象执行的有限循序 0为最高优先级级 -->
<load-on-startup>1</load-on-startup>
Servlect对象被创建出来后,Tomcat服务器马上调用Servlect调用的init方法。
用户发送第二三次请求时,Servlrct对象并没有新建,还是使用原来的Servlet对象。
Servlect对象是单例的
无参构造方法、init方法只在第一次用户发送请求的时候执行。
每发送一次请求Service方法就执行一次。
Tomcat关闭时,则执行destroy()方法。Servlrct并没销毁(即将销毁),destroy()方法执行结束之后Servlrct对象才会销毁,内存释放。
关于Servlect类中方法的调用次数
构造方法只执行一次
Init方法只执行一次
Service用户每请求一次则执行一次
Destroy只执行一次
Tomcat安装
Linux安装Tomcat (linux-x86-arm-mips)安装Tomcat 9.0-云社区-华为云
Windos配置Tomcat
关于Tomcat服务器的目录
bin: 该目录是Tomcat服务器的命令文件存放的目录,打开关闭Tomcat
conf: 该目录是Tomcat服务器的配置文件存放目录。(Server.xml文件中可以配置端口号,默认Tomcat端口是8080)
lib: 该目录是Tom服务器核心程序目录,因为Tomcat服务器是java语言编写的,这里的jar包里面都是class文件。
logs: Tomcat服务器的日志目录,Tomcat服务器启动等信息都会在这个目录下生成日志文件。
temp: Tomcat服务器的临时目录。存储在临时文件。
webapps: 该目录当中就是用来存放大量的webapp(web application web应用)
work: 该目录
windos启动tomcat
或
浏览器访问
http://localhost:8080/
案例
环境:IDEA2022+JDK1.8
技术栈:Servlet+JSP+Mybatis+Tomcat9
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>Servlet-Mybatis2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- mybatis 依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--加入servlet依赖(servlet的jar)-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!--jsp的依赖(jsp相关的jar加进来)-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<!--所在的目录-->
<directory>src/main/java</directory>
<includes>
<!--包括目录下的.properties .xml文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
mybatis-config.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- default必须和environment值一样-->
<environments default="myuser">
<!--environment可以有多个 但id唯一-->
<environment id="myuser">
<!--transactionManager,mybatis的事务类型 commit rollback-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://IP:3306/mysql?"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<!-- mapper sql映射文件的位置 target/classes类路径-->
<mappers>
<mapper resource="com/mybatis/TTT111Dao.xml"/>
</mappers>
</configuration>
MyBatisUtils工具类
package com.mybatis;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* @author QGS
* @version 1.0.0
* @date 2023年02月25日 21:42:04
* @packageName com.mybatis
* @className MyBatisUtils
* @describe TODO
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
String config="mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(config);
//创建SqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//获取sqlSession的方法,非自动提交事务
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
if (sqlSessionFactory!=null){
sqlSession = sqlSessionFactory.openSession();//非自动提交事务
}
return sqlSession;
}
//获取sqlSession的方法,自动提交事务
public static SqlSession getSqlSessionAuto(){
SqlSession sqlSession = null;
if (sqlSessionFactory!=null){
sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
}
return sqlSession;
}
}
Dao接口
package com.mybatis;
import com.Object.TTT111;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author QGS
* @version 1.0.0
* @date 2023年02月25日 21:15:35
* @packageName com.mybatis
* @className TTT111Dao
* @describe TODO
*/
public interface TTT111Dao {
List<TTT111> selectALL();
TTT111 selectById(int id);
int deleteById(int id);
//通过对象传值
int modify(TTT111 ttt111);
//通过@Param()传值
int save(@Param("id") int id ,@Param("name") String name,@Param("address") String address);
}
mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.TTT111Dao">
<select id="selectALL" resultType="com.Object.TTT111">
SELECT id,name,address FROM TTT11
</select>
<select id="selectById" resultType="com.Object.TTT111">
SELECT id,name,address FROM TTT11 Where id=#{id}
</select>
<delete id="deleteById">
delete from TTT11 where id=#{id}
</delete>
<update id="modify">
UPDATE TTT11 SET name=#{name},address=#{address} WHERE id=#{id}
</update>
<insert id="save">
insert into TTT11 values(#{id},#{name},#{address})
</insert>
</mapper>
实现类
get+set+有参无参构造+重写equals and hashCode
Servlet
package com.servlect.service;
import com.Object.TTT111;
import com.mybatis.MyBatisUtils;
import com.mybatis.TTT111Dao;
import org.apache.ibatis.session.SqlSession;
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.io.PrintWriter;
import java.util.List;
/**
* @author QGS
* @version 1.0.0
* @date 2023年03月03日 20:26:22
* @packageName com.servlect.service
* @className MouldServlet
* @describe TODO
*/
@WebServlet({"/list/renew","/list/edit","/list","/list/detail","/list/delete","/list/save"})
public class MouldServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//获取
String servletPath = request.getServletPath();
if ("/list/renew".equals(servletPath)){
renew(request,response);
}else if ("/list/edit".equals(servletPath)){
edit(request,response);
}else if ("/list".equals(servletPath)){
list(request,response);
}else if ("/list/detail".equals(servletPath)){
detail(request,response);
}else if ("/list/delete".equals(servletPath)){
delete(request,response);
}else if ("/list/save".equals(servletPath)) {
save(request, response);
}else {
PrintWriter out = response.getWriter();
out.print("访问路径不存在!");
}
}
private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String address = request.getParameter("address");
//执行数据库insert语句
SqlSession sqlSession = MyBatisUtils.getSqlSessionAuto();
TTT111Dao mapper = sqlSession.getMapper(TTT111Dao.class);
int save = mapper.save(Integer.parseInt(id), name, address);
if (save==1){
//成功
//转发的是一次请求
response.sendRedirect("/ServletWeb/list");
}else {
//保存失败
response.sendRedirect("/ServletWeb/error");
}
}
private void renew(HttpServletRequest request, HttpServletResponse response) throws IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String address = request.getParameter("address");
//执行数据库selectById语句
SqlSession sqlSession = MyBatisUtils.getSqlSessionAuto();
TTT111Dao mapper = sqlSession.getMapper(TTT111Dao.class);
TTT111 ttt111=new TTT111();
ttt111.setId(Integer.parseInt(id));
ttt111.setName(name);
ttt111.setAddress(address);
int modify = mapper.modify(ttt111);
if (modify==1){
response.sendRedirect("/ServletWeb/list");
}else {
//保存失败
response.sendRedirect("/ServletWeb/error");
}
}
private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String contextPath = request.getContextPath();
String id = request.getParameter("id");
//执行数据库selectById语句
SqlSession sqlSession = MyBatisUtils.getSqlSessionAuto();
TTT111Dao mapper = sqlSession.getMapper(TTT111Dao.class);
TTT111 ttt111 = mapper.selectById(Integer.parseInt(id));
//将集合放入请求域中
request.setAttribute("ttt111",ttt111);
request.getRequestDispatcher("/modify.jsp").forward(request,response);
}
private void list(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
//获取应用的根路径
String contextPath = request.getContextPath();
System.out.println("根路径:"+contextPath);
SqlSession sqlSession = MyBatisUtils.getSqlSessionAuto();
TTT111Dao dao = sqlSession.getMapper(TTT111Dao.class);
List<TTT111> ttt111s = dao.selectALL();
//将集合放入请求域中
request.setAttribute("ttt111s",ttt111s);
//转发
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
private void detail(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String id = request.getParameter("id");
SqlSession sqlSession = MyBatisUtils.getSqlSessionAuto();
TTT111Dao dao = sqlSession.getMapper(TTT111Dao.class);
TTT111 ttt111 = dao.selectById(Integer.parseInt(id));
request.setAttribute("ttt111",ttt111);
request.getRequestDispatcher("/detail.jsp").forward(request,response);
}
private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
int i=0;
try {
SqlSession sqlSession = MyBatisUtils.getSqlSessionAuto();
TTT111Dao dao = sqlSession.getMapper(TTT111Dao.class);
i = dao.deleteById(Integer.parseInt(id));
PrintWriter out = response.getWriter();
out.print("执行成功!影响了"+i+"行");
request.getRequestDispatcher("/list").forward(request,response);
}catch (Exception e){
e.printStackTrace();
}
if (i==1){
response.sendRedirect("/ServletWeb/list");
}else {
//保存失败
response.sendRedirect("/ServletWeb/error");
}
}
}
JSP
<%--
Created by IntelliJ IDEA.
User: 13631
Date: 2023/3/4
Time: 19:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<%--index--%>
<head>
<meta charset="utf-8">
<title>welcome</title>
</head>
<body>
<h1 align="center">OA welcome you</h1>
</br>
<h3 align="center">
<a href="<%=request.getContextPath()%>/list">查看用户列表</a>
</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<%--add.jsp--%>
<html>
<head>
<meta charset="utf-8">
<title>新增用户信息</title>
</head>
<body>
<h1>新增用户信息</h1>
<hr/>
<form action="<%=request.getContextPath()%>/list/save" method="post">
id<input type="text" name="id"/><br/>
姓名<input type="text" name="name"/><br/>
地址<input type="text" name="address"/><br/>
<input type="submit" value="save"/><br/>
</form>
<br />
<a href="<%=request.getContextPath()%>/index.jsp">返回主页面</a>
</body>
</html>
<!DOCTYPE html>
<html>
<%--delect--%>
<head>
<meta charset="utf-8">
<title>删除用户信息</title>
</head>
<body>
<h1>删除用户信息</h1>
<hr/>
<form action="" method="post">
id<input type="text" name="id"/><br/>
<input type="submit" value="delect"/><br/>
</form>
<a href="<%=request.getContextPath()%>/index.jsp">返回主页面</a>
</body>
</html>
<%@ page import="com.Object.TTT111" %><%--
Created by IntelliJ IDEA.
User: 13631
Date: 2023/3/4
Time: 22:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<%--detail--%>
<head>
<meta charset='utf-8'>
<title>用户详情</title>
</head>
<body>
<h1 align='center'>用户详情</h1>
<hr/>
<table border='1px' align='center' width='50%'>
<tr>
<th>序号</th>
<th>名称</th>
<th>地址</th>
</tr>
<%
TTT111 ttt111 = (TTT111)request.getAttribute("ttt111");
%>
<tr>
<td><%=ttt111.getId()%></td>
<td><%=ttt111.getName()%></td>
<td><%=ttt111.getAddress()%></td>
<td>
<a href="<%=request.getContextPath()%>/index.jsp">返回主页面</a>
</td>
</tr>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<%--error--%>
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<h1> 操作失败<a href="javascript:void(0)" onclick="window.history.back()">返回</a> </h1>
</body>
</html>
<%@ page import="java.util.List" %>
<%@ page import="com.Object.TTT111" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<%--list--%>
<head>
<meta charset="utf-8">
<title>用户列表</title>
<script type="text/javascript">
function delect(id){
if(window.confirm("删除不可恢复哟!")){
document.location.href ="<%=request.getContextPath()%>/list/delete?id="+ id;
}
}
</script>
</head>
<body>
<h1 align="center">用户列表</h1>
<hr/>
<table border="1px" align="center" width="50%">
<tr>
<th>序号</th>
<th>名称</th>
<th>地址</th>
<th>操作</th>
</tr>
<%
//从request域当中取出集合
List<TTT111> ttt111s =(List<TTT111>)request.getAttribute("ttt111s");
for (TTT111 ttt111 : ttt111s) {
%>
<tr>
<td><%=ttt111.getId()%></td>
<td><%=ttt111.getName()%></td>
<td><%=ttt111.getAddress()%></td>
<td>
<a href="javascript:void(0)" onclick="delect(<%=ttt111.getId()%>)">删除</a>
<a href="<%=request.getContextPath()%>/list/edit?id=<%=ttt111.getId()%>">修改</a>
<a href="<%=request.getContextPath()%>/list/detail?id=<%=ttt111.getId()%>">详情</a>
<a href="<%=request.getContextPath()%>/index.jsp">返回主页面</a>
</td>
</tr>
<%
}
%>
</table>
<a href="add.jsp">新增</a>
</body>
</html>
<%@ page import="com.Object.TTT111" %><%--
Created by IntelliJ IDEA.
User: 13631
Date: 2023/3/4
Time: 23:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<%--modify--%>
<head>
<meta charset="utf-8">
<title>修改用户信息</title>
</head>
<body>
<h1 align="center">修改用户信息</h1>
<hr/>
<%
TTT111 ttt111 =(TTT111) request.getAttribute("ttt111");
%>
<center>
<form action=<%=request.getContextPath()%>/list/renew" method="post" >
i d: <input type="text" name="id" value="<%=ttt111.getId()%>"readonly /><br/>
姓名: <input type="text" name="name" value="<%=ttt111.getName()%>" /><br/>
地址: <input type="text" name="address" value="<%=ttt111.getAddress()%>" /><br/>
<input type="submit" value="提交"/><br/>
</form><br/>
<a href="<%=request.getContextPath()%>/index.jsp">返回主页面</a>
</center>
</body>
</html>
效果
如有错误请指正,谢谢