Tomcat是JAVA Web项目的容器之一,我们的Servlet,JSP放在JAVA容器中才能发挥作用
从Tomcat官网上下载Tomcat的压缩包,不用安装直接放在任意目录下,进入Tomcat安装目录下的bin,双击startup.bat运行,在浏览器中输入localhost:8080可以看到Tomcat的默认页面即可
如果你已经安装好了JAVA环境,也下载好了TOMCAT,那么下载我们来做一个简单的Servlet案例吧!
其实Servlet是放在服务器端运行的JAVA代码,这是一段简单的Servlet代码:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
}
}
编译:
javac HelloWorld.java
报错了:
HelloWorld.java:2: 错误: 程序包javax.servlet不存在
import javax.servlet.*;
HelloWorld.java:3: 错误: 程序包javax.servlet.http不存在
import javax.servlet.http.*;
查了资料,由于servlet和JSP不是java平台j2se(标准版)的一部分,而是j2EE的一部分,因此必须告知编译器servlet的位置
在配置JAVA的环境变量时,配置ClassPath为Java加载类路径
我们直接在系统变量中添加classpath的值:
Tomcat安装路径\lib\servlet-api.jar
重启电脑
可以成功编译,在C:\apache-tomcat-9.0.53\webapps\ROOT\WEB-INF下新建目录classes,把编译好的classes文件放进去。
编辑web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<!-- 声明Servlet对象 -->
<servlet-name>HelloWorld</servlet-name>
<!-- 上面一句指定Servlet对象的名称 -->
<servlet-class>HelloWorld</servlet-class>
<!-- 上面一句指定Servlet对象的完整位置,包含包名和类名 -->
</servlet>
<servlet-mapping>
<!-- 映射Servlet -->
<servlet-name>HelloWorld</servlet-name>
<!--<servlet-name>与上面<Servlet>标签的<servlet-name>元素相对应,不可以随便起名 -->
<url-pattern>/HelloWorld</url-pattern>
<!-- 上面一句话用于映射访问URL -->
</servlet-mapping>
</web-app>
启动Tomcat服务进入Tomcat的安装目录下的bin,双击startup.bat
在浏览器中输入localhost:8080\HelloWorld
第一个Servlet运行成功!