Spring集成Web环境搭建

发布于:2025-03-31 ⋅ 阅读:(21) ⋅ 点赞:(0)

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

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

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

自行配置逻辑应是如下:

首先是Controller层

public class UserController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, 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 {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");

        sce.getServletContext().setAttribute("applicationContext", contextConfigLocation);
        System.out.println("ContextLoaderListener contextInitialized");
    }

    @Override
    public 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配置文件中进行相应修改即可。


网站公告

今日签到

点亮在社区的每一天
去签到