配置全局参数
全局参数主要是为了解耦。
位置:web / WEB-INF / web.xml
<!-- 全局参数-->
<context-param>
<param-name>contextConfigLocation</param-name>(参数标识)
<param-value> classpath:applicationContext.xml</param-value>(文件映射,映射的是一个spring配置文件,给监听器联系其创建上下文对象)
</context-param>
配置监听器
监听器listener
配置的目的是为了在业务请求时,监听到后创建ApplicationContext
对象。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext=servletContextEvent.getServletContext();//获取域对象
//servletContext对象可以获取全局参数
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
//根据全局参数映射的spring配置文件(applicationContext.xml)创建到上下文对象
ApplicationContext app=new ClassPathXmlApplicationContext(contextConfigLocation);
//将上下文对象存储到ServletContext域中
servletContext.setAttribute("app",app);//存进域对象
System.out.println("容器创建完毕");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
将监听器配置到xml文件中
位置:web / WEB-INF / web.xml
位置:web / WEB-INF / web.xml
<listener>
<listener-class>spring.mvc.listener.ContextLoaderListener</listener-class>
</listener>
ps: <listener-class>映射的地址是手动编写的监听器的全限定名,如果是自动的则应该配置如下:
<!--自动-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
web层
public class uServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext=this.getServletContext();//获取监听器创建的servletContext
//用封装好的工具,传入servletContext根据其获得上下文
WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
省略xxx业务-------------------
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}