Spring在Web项目中的应用-添加ServletContext监听器

    xiaoxiao2021-04-18  58

    添加ServletContext监听器

    ServletContext初始化时创建Spring容器

    获取容器

    package com.hk.ssh.servlets; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.context.WebApplicationContext; import com.hk.ssh.beans.Student; import com.hk.ssh.service.IStudentService; public class RegisterServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); String ageStr = request.getParameter("age"); Integer age = Integer.valueOf(ageStr); Student student = new Student(name,age); //1、创建Spring 容器(这种创建方式每来一次请求就会创建一个ApplicationContext) //ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); /** * 采用如下方式创建Spring容器,在ServletContext初始化是创建容器 * ServletContext只初始化一次,所以整个web运用都只会有一个Spring容器 */ ServletContext application = request.getSession().getServletContext(); WebApplicationContext ac = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); //2、从容器中获取Service对象 IStudentService service = (IStudentService) ac.getBean("studentService"); //3、调用Service的addStudent() service.addStudent(student); request.getRequestDispatcher("/welcome.jsp").forward(request, response); } }

    获取Spring容器还有一个方法

    WebApplicationContext ac =WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

    web.xml

    <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 加载Spring配置文件 文件的位置和名称是可变的,且配置文件可以有多个 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 注册ServletContext监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>Register-Servlet</servlet-name> <servlet-class>com.hk.ssh.servlets.RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Register-Servlet</servlet-name> <url-pattern>/registerServlet</url-pattern> </servlet-mapping> </web-app>

    完整项目源码:http://pan.baidu.com/s/1slEY7JR

    转载请注明原文地址: https://ju.6miu.com/read-674839.html

    最新回复(0)