• javaWeb使用spring框架时在配置上的编程技巧


     在上一篇文章Spring之IOC_数字公民某杨的博客-CSDN博客

    中使用spring后,示例代码中有两行

    ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    studentLoginService = (StudentLoginService) ac.getBean("studentLoginService");

    这两行代码的意思是,获取spring容器 ac ,然后从ac对象中获取studentLoginService对象。

    在这里有些技巧,

    一个是ac这个spring容器对象创建好以后,实际只需要从里面获取studentLoginService对象,希望用垃圾回收机制尽快回收ac。

    而当方法结束时,方法出栈,对对象的引用ac变量销毁,这样就启动java垃圾回收机制,回收原来ac指向的对象。如果还是放在servlet的service方法中,servlet对象只创建一次,但是service方法应该是多线程调用,所以会造成多次创建ac对象。而我们知道servlet有个init方法,是在servlet对象创建时调用,这样就想到把ac创建代码放在init方法中,我们有:

    public class StudentServlet extends HttpServlet {
        private StudentLoginService studentLoginService;
    
        @Override
        public void init() throws ServletException {
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
            studentLoginService = (StudentLoginService) ac.getBean("studentLoginService");
        }
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String name = req.getParameter("name");
            String address = req.getParameter("address");
            try {
                Student student = studentLoginService.studentLogin(name, address);
    
    
                HttpSession session = req.getSession();
                ServletContext servletContext = this.getServletContext();
                HttpSession tempSession = (HttpSession) servletContext.getAttribute(student.getId()+"");
                if(tempSession!=null){
                    tempSession.invalidate();
                }else {
                    servletContext.setAttribute(student.getId()+"", session);
                }
                session.setAttribute("student", student);
    
                resp.sendRedirect("sucess.jsp");
            }catch (Exception e){
                resp.sendRedirect("error.jsp");
            }
        }

    另一个技巧体现在web.xml配置文件中,先看下图:

     

    我们有web.xml:


        contextConfigLocation
        classpath:spring-config.xml


    这个配置是说,在servletContext对象中保存以contextConfigLocation为key,以classpath:spring-config.xml为值的数据。这样当spring=config.xml后面需要修改的时候,就不需要去代码里面修改。


        org.springframework.web.context.ContextLoaderListener

    这个配置的意思是监听servletContext对象的创建,然后在监听器中,实现spring配置文件内容的读取。由于servlet对象只有1个,这样就减少了servlet创建多次时,对spring-config.xml文件的多次io操作

  • 相关阅读:
    【HackTheBox】 meow
    宝宝蛋白过敏怎么办
    Java的动态代理Proxy.newProxyInstance
    跨模态神经搜索实践VCED 基于Streamlit实现前端页面设计和逻辑
    激光雷达构建地图( 覆盖栅格建图)
    Typora+博客园搭建图床
    Qt中文乱码常量换行符终极解决方案
    前置过滤器安错了,是过滤不了水里的虫卵的
    业务架构、应用架构、技术架构、数据架构
    基于transformer的心脑血管心脏病疾病预测
  • 原文地址:https://blog.csdn.net/m0_47161778/article/details/126697389