天天看点

java web 数据字典_JAVA web 数据字典包括基础数据的加载--减少数据库查询次数

1.为什么要把数据字典和基础数据放在ServletContext?

因为数据字典是,整个网站使用的是同一份。所以可以在网站启动的时候,就查询放在ServletContext里面就可以。这样就不用每次请求过来的时候再多次查询数据库。

--使用过滤, 不好。 因为此次请求过来,都必须要拦截过滤器。

--使用Servlet , 不好, 因为此次请求过来,都必须要执行对应路径的servlet

--所以,我们需要有一个技术。在启动Tomcat的时候就加载一次,后面就不会再加载了。

2.需要解决的问题

问题1:创建Spring容器是需要指定配置文件或者配置类的位置的。而监听器是没有设置初始化参数的入口的。如何解决?

答:通过可以将参数放在全局的context容器里面。那么所有的web组件的对象都可以访问了。

问题2:监听器是属于Tomcat Web服务器的技术,所以对象并没有放在Spring容器里面。是无法通过注入的方式获得Spring容器的对象的。如何在监听器里面获得Spring容器的对象呢?

答:对于不是Spring容器里面的对象要获得Spring容器里面的对象。Spring框架提供了一个WebApplicationContextUtils工具类可以获得Spring容器的对象。

packagecn.gzsxt.listener;importjava.util.List;importjava.util.Map;importjavax.servlet.ServletContext;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.context.WebApplicationContext;importorg.springframework.web.context.support.WebApplicationContextUtils;importcn.gzsxt.service.DictionaryService;public class DictionaryCreateListener implementsServletContextListener {//@Autowired//private DictionaryService dictionaryService;

@Overridepublic voidcontextInitialized(ServletContextEvent sce) {// WebApplicationContext applicationContext =WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

DictionaryService dictionaryService= applicationContext.getBean(DictionaryService.class);

List> dictionarys =dictionaryService.findAllDictionary();

ServletContext context=sce.getServletContext();

context.setAttribute("dictionarys", dictionarys);

}

@Overridepublic voidcontextDestroyed(ServletContextEvent sce) {

}

}

web.xml的配置

characterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

characterEncodingFilter

/*

dispatcherServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

contextClass

org.springframework.web.context.support.AnnotationConfigWebApplicationContext

1

dispatcherServlet

/

contextConfigLocation

cn.gzsxt.config

contextClass

org.springframework.web.context.support.AnnotationConfigWebApplicationContext

org.springframework.web.context.ContextLoaderListener

cn.gzsxt.listener.InitDataCreateListener