Eclipse JSP/Servlet
在 Eclipse 里建 Dynamic Web Project、配 Tomcat、调试 JSP。
Key PointsEclipse 的 Dynamic Web Project 就是标准 Web 应用结构,配好 Tomcat 运行时后可直接部署调试。
建项目
File → New → Dynamic Web ProjectTarget runtime选已配置的 Tomcat;没有就点New Runtime添加Dynamic web module version选 5.0 或 6.0(对应 Servlet 5/6)- 勾选
Generate web.xml deployment descriptor
Text
MyWeb/
├── src/ # Java 源码,编译到 WEB-INF/classes
│ └── com/example/Hello.java
├── WebContent/ # 或 src/main/webapp(取决于版本)
│ ├── index.jsp
│ ├── WEB-INF/
│ │ ├── web.xml
│ │ └── lib/
│ └── META-INF/
└── build/ # 编译产物配置 Tomcat 运行时
Window → Preferences → Server → Runtime Environments → Add, pick the Tomcat version and point to its install directory and JRE. Then tick it under the project's Targeted Runtimes, or HttpServlet will not compile.
部署与运行
Text
右键项目 → Run As → Run on Server
→ 选 Tomcat
→ 浏览器打开 http://localhost:8080/MyWeb/index.jspEclipse deploys via workspace metadata by default, so moving the project does not break it. To deploy into Tomcat's own webapps, double-click the server in the Servers view and set Server Locations to Use Tomcat installation.
调试 JSP
- 断点 —— JSP 里也能下断点,Eclipse 会把它映射到翻译后的
_jspService - 热更新 —— 改 JSP 保存后刷新浏览器即可,不需要重启
- 改 Java 类 —— 需要重新部署,或装 JRebel 之类的热替换插件
A red cross in the
Servers view means read the Console stack first. The two usual causes are a busy port and a wrong servlet class name in web.xml producing ClassNotFoundException.推荐设置
| Setting | Value | Why |
|---|---|---|
| JSP encoding | UTF-8 | 避免中文乱码 |
| JSP editor | 带语法高亮的 JSP Editor | 比纯文本好读 |
| Auto reload | 开启 | 改完刷新即生效 |
建项目
File → New → Dynamic Web ProjectTarget runtime选已配置的 Tomcat;没有就点New Runtime添加Dynamic web module version选 5.0 或 6.0(对应 Servlet 5/6)- 勾选
Generate web.xml deployment descriptor
Text
MyWeb/
├── src/ # Java 源码,编译到 WEB-INF/classes
│ └── com/example/Hello.java
├── WebContent/ # 或 src/main/webapp(取决于版本)
│ ├── index.jsp
│ ├── WEB-INF/
│ │ ├── web.xml
│ │ └── lib/
│ └── META-INF/
└── build/ # 编译产物配置 Tomcat 运行时
Window → Preferences → Server → Runtime Environments → Add,选 Tomcat 版本,指定安装目录和 JRE。配好后项目的 Targeted Runtimes 要勾上它,否则 HttpServlet 编译不过。
部署与运行
Text
右键项目 → Run As → Run on Server
→ 选 Tomcat
→ 浏览器打开 http://localhost:8080/MyWeb/index.jspEclipse 默认用「工作空间内的元数据」部署,项目目录变了也不会断。想部署到 Tomcat 的 webapps 下,在 Servers 视图双击服务器,把 Server Locations 改成 Use Tomcat installation。
调试 JSP
- 断点 —— JSP 里也能下断点,Eclipse 会把它映射到翻译后的
_jspService - 热更新 —— 改 JSP 保存后刷新浏览器即可,不需要重启
- 改 Java 类 —— 需要重新部署,或装 JRebel 之类的热替换插件
Eclipse 的
Servers 视图里如果出现红色叉,先看 Console 里的堆栈。最常见的两个原因:端口被占、web.xml 里的 Servlet 类名写错导致 ClassNotFoundException。推荐设置
| 设置 | 值 | 原因 |
|---|---|---|
| JSP 编码 | UTF-8 | 避免中文乱码 |
| JSP 编辑器 | 带语法高亮的 JSP Editor | 比纯文本好读 |
| 自动重载 | 开启 | 改完刷新即生效 |