Eclipse JSP/Servlet

在 Eclipse 里建 Dynamic Web Project、配 Tomcat、调试 JSP。

Beginner
Key PointsEclipse 的 Dynamic Web Project 就是标准 Web 应用结构,配好 Tomcat 运行时后可直接部署调试。

建项目

  1. File → New → Dynamic Web Project
  2. Target runtime 选已配置的 Tomcat;没有就点 New Runtime 添加
  3. Dynamic web module version 选 5.0 或 6.0(对应 Servlet 5/6)
  4. 勾选 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.jsp

Eclipse 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.

推荐设置

SettingValueWhy
JSP encodingUTF-8避免中文乱码
JSP editor带语法高亮的 JSP Editor比纯文本好读
Auto reload开启改完刷新即生效

Friends & Partners