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:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-config.xml</param-value>
</context-param>

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

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值