一、安装Tomcat
1、下载解压
http://tomcat.apache.org/
清华下载源:apache-tomcat-7.0.100.tar.gz
2、配置环境变量
$ cat ~/.bash_profile
# tomcat
export CATALINA_HOME="具体的路径"
export PATH="$CATALINA_HOME/bin":$PATH
3、启动停止
$ startup.sh
$ shutdown.sh
访问测试:
http://localhost:8080/
参考
Servlet 环境设置
二、配置虚拟目录
网上看到的Tomcat和Servlet关系图
图片来源:https://blog.csdn.net/dzy_water/article/details/79704600
图片来源:https://blog.csdn.net/baidu_36583119/article/details/79642407
配置虚拟目录,将路径指向开发目录
按如下路径,新建一个文件:webapp.xml
$cat tomcat/conf/Catalina/localhost/webapp.xml
<Context path="/demo" docBase="/root/webapp" crossContext="true" debug="3" privileged="true" reloadable="true" debug="true"></Context>
属性说明:
crossContext 在应用内返回在该虚拟主机上运行的其他web application的request dispatcher
docBase 文档基准目录,可以使用绝对路径,也可以使用相对于context所属的Host的appBase路径。
override 如果想利用该Context元素中的设置覆盖DefaultContext中相应的设置
privileged 允许context使用container servlets,比如manager servlet。
path web应用的context路径
reloadable 自动重载web
debug 调试模式
目录结构如下
webapp
├── WEB-INF
│ ├── classes
│ │ ├── AServlet.class
│ └── web.xml
└── hello.html
1、先确保能够访问静态文件,说明虚拟目录配置成功
hello.html
<h1>hello</h1>
访问路径:
http://localhost:8080/demo/hello.html
2、不管*.java
文件在哪里,需要指定*.class
生路径为:
webapp/WEB-INF/classes
文件内容如下:
AServlet.java
import javax.servlet.*;
import java.io.IOException;
public class AServlet implements Servlet{
// 创建时执行
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init");
}
// 获取配置信息
@Override
public ServletConfig getServletConfig() {
System.out.println("getServletConfig");
return null;
}
// 处理请求
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service");
servletResponse.getWriter().write("Hello");
}
// 获取servlet信息
@Override
public String getServletInfo() {
System.out.println("getServletInfo");
return null;
}
// 销毁前调用
@Override
public void destroy() {
System.out.println("destroy");
}
}
配置url和servlet映射关系
web.xml
<?xml version="1.0" encoding="utf-8" ?>
<web-app>
<!-- 注册 Servlet,帮助web服务器反射该类 -->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>AServlet</servlet-class>
</servlet>
<!-- 映射 Servlet 资源,用url-pattern元素标示 URL -->
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
访问路径:
http://localhost:8080/demo/hello