欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > Spring集成Web环境搭建

Spring集成Web环境搭建

2025/6/28 5:38:53 来源:https://blog.csdn.net/Hellyc/article/details/146571358  浏览:    关键词:Spring集成Web环境搭建

一、自行创建监听器来模拟springweb架构中的监听器流程

监听器的作用:当web服务器开始启动时,使用监听器监听初始化周期,并将spring配置文件放置在Servlet的最大域中。一旦服务器启动后就可以直接从域中使用gertAtribute方法去获取到spring的配置文件applicationContext.xml。

然后会设置一个工具类,通过工具类作为中介来返回配置文件信息。

自行配置逻辑应是如下:

首先是Controller层

public class UserController extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {//调用applicationContext配置文件首先通过工具类WebApplicationContextUtils//再通过该类中的getApplicationContext从最大域中获得监听器上传的getApplicationContext配置文件内容//调用顺序为:WebApplicationContextUtils  ->  getApplicationContext// ->  (ApplicationContext) servletContext.getAttribute("applicationContext")ApplicationContext applicationContext =WebApplicationContextUtils.getApplicationContext(req.getServletContext());userService = (UserService) applicationContext.getBean("userService");userService.save();}

然后是web.xml配置文件

<web-app><display-name>Archetype Created Web Application</display-name>
  <context-param><param-name>contextConfigLocation</param-name><param-value>applicationContext.xml</param-value></context-param>
<!--  监听器配置--><listener><listener-class>listener.ContextLoaderListener</listener-class></listener>
  <servlet><servlet-name>UserController</servlet-name><servlet-class>com.hxy.usercontroller.UserController</servlet-class></servlet><servlet-mapping><servlet-name>UserController</servlet-name><url-pattern>/userController</url-pattern></servlet-mapping>
</web-app>

监听器类的创建

public class ContextLoaderListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {ServletContext servletContext = sce.getServletContext();String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");sce.getServletContext().setAttribute("applicationContext", contextConfigLocation);System.out.println("ContextLoaderListener contextInitialized");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {}
}
工具类的创建
//设置一个工具,用于返回spring配置类:applicationContext
//外部只需要调用这个类的方法getApplicationContext,就能够得到返回的applicationContext
public class WebApplicationContextUtils {public static ApplicationContext getApplicationContext(ServletContext servletContext) {return (ApplicationContext) servletContext.getAttribute("applicationContext");}
}

二、使用spring框架中的监听器直接创建项目

只需将web.xml中的监听器配置文件改为spring-web框架自带的,同时在Controller层获取配置文件时调用spring框架自带的工具类即可,省去了创建监听器以及工具类的过程

三、总结

使用监听器的作用是简化提取配置文件的过程,方便操作。

监听器的作用在于监听web服务器的初始化过程,将配置文件进行传递,从而方便后续的获取。

通过监听器的模式,实现了解耦,如果修改了配置文件的名称或内容,将不必再在代码中重复修改,这个过程只需要在web.xml配置文件中进行相应修改即可。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词