http:默认端口80
https:默认端口443
tomcat的目录结构
配置tomcat
在环境变量里要有JAVA_HOME,jdk的位置。
CATALINA:tomcat的位置。(可以不用配置)
如果这两个没有配置好,启动bin/startup.bat,会出现闪退。
启动之后会出现乱码,在config/logging.properties里把java.util.logging.ConsoleHandler.encoding = UTF-8注释掉
就不会出现乱码。
配置虚拟主机
1.关闭服务
2.打开config/server.xml,划到最后,
复制一份,放在后面,改一下name,appBase.
在webapps的同级目录下,创建yh,
里面在创建
里面放入自己的html
找到C:\Windows\System32\drivers\etc路径下的hosts文件,在最后面添加127.0.0.1 yh
保存(有可能不能修改,复制一份,放在桌面,修改之后,替换就可以)。
启动服务,打开网页,输入http://yh:8080,就是你的网页了。
项目部署到Tomcat
WEB-INF文件夹是不能访问的。
404:访问资源不存在
500:服务器错误,程序有异常
虚拟目录
在webapps目录下,没有这个目录,可以通过虚拟目录指向真实项目的位置。
在server.xml中配置虚拟目录。
<Context docBase="d:\aaa" path="/aaa"/>
servlet
手工创建Servlet
项目首页设置
在WEB-INF中,修改web.xml
<welcome-file-list>
<welcome-file>index1.html</welcome-file>
<welcome-file>index.xhtml</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
中间是你自己设置的网页
网站错误页面
<error-page>
<error-code>404</error-code>
<location>/error/error404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/error500.html</location>
</error-page>
<error-page>
<location>/error/error500.html</location>
</error-page>
<!-- ./ 返回父级目录-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>500出错了</title>
</head>
<body>
<img src="./img/2.jpg" width="100%" >
</body>
</html>
为什么tomcat中没有相关的文件,IDEA却可以运行程序。这里就用到了虚拟目录,当我们用IDEA运行tomcat时我们能发现
根据第一个CATALINA_BASE目录,找到相关路径
C:\Users\xx.IntelliJIdea2019.3\system\tomcat\Tomcat_8_5_57_0827web\conf\Catalina\localhost里面有个web.xml文件,打开之后
这就是为什么能运行的原因。
这里就是idea配置虚拟目录的地方。
简单实现tomcat
tomcat的原理很简单,接受客户端请求,把本地文件传送到客户端。虽然原理很简单, 但是其中有很多复杂的问题。我就简单实现一下他的原理。
public class TomcatServer {
public static void main(String[] args) {
ServerSocket tomcatServer = null;
Socket socket = null;
OutputStream writer = null;
FileInputStream reader = null;
try {
tomcatServer = new ServerSocket(8888);
System.out.println("服务器开启服务");
while (true) {
socket = tomcatServer.accept();
//获得输出流
writer = socket.getOutputStream();
//获得输入流
reader = new FileInputStream("D:\\first.html");
//缓冲区
byte[] buffer = new byte[1024*4];
int len = 0;
while((len = reader.read(buffer))!=-1){
writer.write(buffer);
writer.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
socket.close();
tomcatServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这样我们打开网页,输入http://服务器地址:8888就可以访问。