1.基本三层架构环境搭建
1).目录结构:
2).代码
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
UserDaoImpl:
UserServiceImpl:
applicationContex.xml:
UserServlet:
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=app.getBean(UserService.class);
userService.save();
}
}
web.xml:配置userServlet
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
3).测试
通过tomcat发布,http协议访问。localhost:8080默认访问的是index.jsp,所以不要忘了写默认jsp.
web层调业务层,业务层调dao层,在dao层进行代码的输出
2.Spring集成web环境代码实现
Spring提供监听器ContextLoaderLisetener,该监视器内部加载Spring配置文件,创建上下文对象,并存储到ServletContxt域中,提供一个客户端工具WebApplicationContexttUtils供使用者获得相应的上下文对象。
1.pom.xml导坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2.web.xml中配置监听器
<!--全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.UserSerlet:
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext=this.getServletContext();
ApplicationContext app= WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService=app.getBean(UserService.class);
userService.save();
}
}