微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐