开发环境准备
-
工具安装
- Eclipse IDE:下载 Eclipse IDE for Enterprise Java Developers 版本(内置Web工具)。
- JDK:配置Java 17(推荐LTS版本)。
- 服务器:Apache Tomcat 10.x(与Servlet 5.0+兼容)。
- 数据库:MySQL 8.0 + Connector/J驱动。
-
Eclipse配置
路径:Window → Preferences → Server → Runtime Environments
添加Tomcat路径,指定JRE为JDK 17,避免默认JRE冲突。
实战:员工管理系统开发
步骤1:创建动态Web项目
- 选择 File → New → Dynamic Web Project
- 项目名:
EmployeeSystem - 勾选 Generate web.xml(兼容传统配置)
- 目录结构自动生成:
├── src(Java源码) ├── WebContent │ ├── WEB-INF │ │ └── lib(依赖JAR包) │ └── index.jsp
步骤2:连接数据库
核心代码:JDBC工具类
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/emp_db?useUnicode=true&characterEncoding=UTF-8";
private static final String USER = "root";
private static final String PASSWORD = "secure123";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
避坑指南:
- 添加
mysql-connector-java-8.0.30.jar到WEB-INF/lib- 解决中文乱码:连接串中强制指定
characterEncoding=UTF-8
步骤3:Servlet开发(MVC控制器)
员工查询Servlet示例
@WebServlet("/list-employees")
public class EmployeeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try (Connection conn = DBUtil.getConnection()) {
List<Employee> employees = new ArrayList<>();
String sql = "SELECT id, name, department FROM employees";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ResultSet rs = ps.executeQuery();
while (rs.next()) {
employees.add(new Employee(
rs.getInt("id"),
rs.getString("name"),
rs.getString("department")
));
}
}
request.setAttribute("employeeList", employees);
request.getRequestDispatcher("/employee-list.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Database error", e);
}
}
}
步骤4:JSP视图渲染
employee-list.jsp关键代码
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<table class="table">
<tr>
<th>ID</th><th>姓名</th><th>部门</th>
</tr>
<c:forEach items="${employeeList}" var="emp">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.department}</td>
</tr>
</c:forEach>
</table>
安全增强:
使用JSTL代替<%= %>脚本,避免XSS攻击(如<c:out value="${emp.name}"/>)
步骤5:部署与调试
-
热部署配置
- 右键项目 → Run As → Run on Server
- 开启自动发布:Server配置中设置
"Automatically publish when resources change"
-
断点调试技巧
- 在Servlet中设置断点 → 右键项目 → Debug As → Debug on Server
- 监控变量:使用Expressions视图实时计算SQL查询条件值
性能优化方案
- 连接池替代JDBC直连
使用Tomcat内置DBCP:<!-- 在META-INF/context.xml中配置 --> <Resource name="jdbc/empDB" auth="Container" type="javax.sql.DataSource" maxTotal="50" maxIdle="10" driverClassName="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/emp_db" />
- JSP预编译
部署前执行:Eclipse菜单 → Project → Clean减少首次访问延迟
为什么选择Eclipse而非IDEA?
- 定制化优势:对老旧项目支持更灵活,可安装插件支持JSF/Struts等传统框架
- 资源消耗低:在8GB内存机器上流畅运行大型Web项目
- 企业级生态:通过TPTP插件实现性能剖析,深度集成WTP规范
下一步挑战:
如果在高并发场景下出现数据库连接泄漏,如何快速定位?
A. 在Tomcat中启用JDBC监控
B. 使用VisualVM分析线程堆栈
C. 配置Druid连接池的Filter统计
欢迎在评论区分享你的排查思路!
原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/30422.html