1.Spring集成web环境
1.为项目添加web框架
2.导入依赖
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.5</version>
</dependency>
</dependencies>
3.持久层和业务层的搭建
项目大致框架为
4.web层实现
public class UserWeb extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) app.getBean("userService");
userService.save();
}
}
5.配置文件(注册servlet和组件扫描)
<!--web.xml-->
<servlet>
<servlet-name>UserWeb</servlet-name>
<servlet-class>com.kk.web.UserWeb</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserWeb</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>
<!--applicationContext.xml-->
<context:component-scan base-package="com.kk"/>
6.添加tomcat
若部署时没有显示如上的Artifacts,可在File->Project Structuere中添加
7.运行结果
当进入/user路径后会出现
2.ApplicationContext应用上下文获取方式(监听器)
- 应用上下文对象是通过new ClasspathXmlApplicationContext(spring配置文件)方式获取的,但是每次从容器中获得Bean时都要编写new ClassnathXmIApplicatianContext(spring配置文件),这样的弊端是配置文件加载多次,应用上下文对象创建多次。
- 在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域ServletContext域中,这样就可以在任意位置从域中获得应用上下文对象。
1.在web.xml中配置Contextloadeclistener监听器(导入spring-web坐标)
<!-- 全局参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2.使用WebADplicationContextUtils获得应用上下文对象ApplicationContext.
public class UserWeb extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = (UserService) app.getBean("userService");
userService.save();
}
}