一、Maven 核心内容
1. 依赖管理
-
依赖传递:
-
<scope>
标签控制依赖传递性:-
test
和provided
作用域的依赖不会传递。 -
compile
作用域的依赖默认传递。
-
-
依赖原则:
-
路径最短优先:优先选择依赖路径短的版本。
-
先声明优先:路径相同时,优先选择先声明的依赖。
-
-
依赖排除:通过
<exclusions>
排除冲突的传递依赖。<exclusions> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions>
-
-
统一版本管理:
-
使用
<properties>
定义全局版本号,例如:<properties> <zxst.junit.version>4.13</zxst.junit.version> <zxst.mysql.version>8.0.26</zxst.mysql.version> </properties>
-
在
<dependencyManagement>
中声明依赖版本,子模块无需重复指定版本。
-
2. 父子工程与聚合
-
父工程:
-
打包方式为
pom
,通过<modules>
聚合子模块。 -
统一管理依赖版本,子模块继承父工程配置。
-
示例父工程配置:
<modules> <module>user_order</module> <module>user_cart</module> </modules>
-
-
子工程:
-
通过
<parent>
标签关联父工程。 -
直接使用父工程声明的依赖,无需指定版本。
<parent> <groupId>com.zxst</groupId> <artifactId>maven_pran</artifactId> <version>1.0-SNAPSHOT</version> </parent>
-
3. Maven 命令
-
clean
:清除target
目录。 -
compile
:编译主程序代码。 -
package
:打包主程序和测试代码。 -
install
:打包并安装到本地仓库。
二、Servlet 核心内容
1. Servlet 入门案例
-
实现方式:
-
XML 配置:在
web.xml
中配置<servlet>
和<servlet-mapping>
。<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>com.zzst.servlet.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/myFirstServlet</url-pattern> </servlet-mapping>
-
注解配置:使用
@WebServlet
简化配置。@WebServlet("/SecondServlet") public class SecondServlet extends HttpServlet { ... }
-
-
请求处理:
-
doGet
和doPost
方法处理不同请求方式。 -
通过
HttpServletRequest
获取请求参数。
-
2. Request 对象
-
参数获取:
-
req.getParameter("key")
:获取单个参数值。 -
req.getParameterValues("hobby")
:获取多选框值(数组)。 -
req.getParameterMap()
:获取所有参数键值对。
-
3. JDBC 整合案例
-
数据库工具类:
-
使用 C3P0 连接池管理数据库连接。
public class ConnectionUtil { static DataSource cpds = new ComboPooledDataSource(); public static Connection getConnection() { ... } }
-
-
DAO 层实现:
-
接口定义与实现类分离,例如
DeptDao
和DeptDaoImpl
。 -
使用预编译语句防止 SQL 注入:
String sql = "insert into dept(dname, local) values(?, ?)"; PreparedStatement ps = connection.prepareStatement(sql);
-
-
Servlet 调用 DAO:
@WebServlet("/thirdServlet") public class ThirdServlet extends HttpServlet { DeptDao dao = new DeptDaoImpl(); protected void doPost(...) { String dname = req.getParameter("dname"); boolean flag = dao.saveInfo(dname, local); } }
三、注意事项与改进建议
-
依赖配置准确性:
-
检查 Maven 坐标,例如
c3p0
的正确坐标为:<dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency>
-