ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring入门笔记--Spring集成web环境

2022-06-19 16:31:19  阅读:152  来源: 互联网

标签:ApplicationContext web -- Spring app ContextLoaderListener servletContext UserSe


Spring集成web环境

idea社区版没有web功能,也不带tomcat插件,需要idea专业版。

IDEA配置

  1. 在项目的modules中增加web模块,并设置路径。
  2. 在Facets中也要新增web模块
  3. 在Artifacts中确保有classes和lib文件夹,我的没有lib,导致启动tomcat时老是报错找不到一些类,因为部署环境上没有。
  4. tomcat设置,添加external source和artifact

maven配置

如果使用tomcat10,javax已经替换成了jakarta,导包要正确,version和JDK版本有关。

<dependency>
    <groupId>com.guicedee.services</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>1.1.1.7-jre8</version>
</dependency>
老版本:
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>

代码

在web项目中,可以使用ServletContextListener监听web应用的启动,web应用启动时,就夹在Spring的配置文件,创建上下文对象ApplicationContext,并存储在最大的域servletContext中。

监视器的实现:

public class ContextLoaderListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        servletContext.setAttribute("app", app);  //存到域中
        System.out.println("ContextLoaderListener.contextInitialized");
    }
}

web.xml中:

<!--全局初始化参数-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

实际上ContextLoaderListener和WebApplicationContextUtils类spring-web已经封装好了,可以直接使用,在获取上下文时:

<listener>
    <!--自己实现的-->
    <listener-class>com.yihao.listener.ContextLoaderListener</listener-class>
    <!--spring-web中有的,可以省略掉servletContext.setAttribute("app", app);的一个中间命名-->
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);

但是如果使用了jakarta.servlet-api兼容有问题,自己写:

ServletContext servletContext = this.getServletContext();
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
UserService userService = app.getBean(UserService.class);

标签:ApplicationContext,web,--,Spring,app,ContextLoaderListener,servletContext,UserSe
来源: https://www.cnblogs.com/xiahounidunye/p/16390240.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有