spring学习 之 spring与java web整合原理示例

spring是一个容器,里面装载着实现业务逻辑的Bean,当一个请求来时,需要servlet拿到这些实现业务逻辑的Bean,而这些Bean被注入到spring容器中,因此需要Servlet程序拿到Spring容器。

javaweb开发中Servlet三大域对象的应用(request、session、application(ServletContext))

Request
request:一个请求链,每一个请求都会创建一个request,作用域为当前的请求链,一般用于同一请求链之间不同页面的参数传递,如表单中的值传递。

Request作用域的特点:
放数据的servlet和取数据的servlet必须保证使用的是同一个request对象。一旦request对象改变了,那么,request作用域里面的值就会失效。

session
session:Tomcat(服务器)会为每个会话创建一个session对象,作用域:session的数据只能在当前会话中的所有servlet共享(会话范围:如某个用户从首次访问服务器开始,到用户关闭浏览器结束),HttpSession底层依赖Cookie。

ServletContext
application(ServletContext): 服务器会为每个web应用创建一个ServletContext对象,而ServletContext对象的创建时在服务器启动时完成的,在服务器关闭时销毁的, 作用:在整个web应用的动态资源之间共享数据。

从上面写的域对象的生命周期以及作用域来看,只有ServletContext适合放spring容器。

1、创建一个ServletContextListener监听器

创建 在监听器中完成spring容器的创建工作,并把创建的spring容器放入tomcat容器的ServletContext域中

package com.web.listener;

import com.web.config.SpringConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebListener
public class SpringContextListener implements ServletContextListener{

    public SpringContextListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String contextConfiguration=servletContext.getInitParameter("contextConfiguration");
        Class<?> configClass = null;
        try {
            configClass = Class.forName(contextConfiguration);
        } catch (ClassNotFoundException e) {
            System.out.println("无法解析配置类");
            throw new RuntimeException("解析配置类异常");
        }
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(configClass);
        servletContext.setAttribute("springContexgt",context);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }


}

2、在web.xml中定义好spring配置类的全路径

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfiguration</param-name>
        <param-value>com.web.config.SpringConfig</param-value>
    </context-param>
</web-app>

3、spring的配置类

package com.web.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.web.service.*")
public class SpringConfig {
}

4、定义一个工具类

定义一个工具类,获取特定的Bean

package com.web.util;

import org.springframework.context.ApplicationContext;

import javax.servlet.ServletContext;

public class WebContextUtil{

    public static<T> T getApplicationContext(ServletContext servletContext,Class<T> requiredType){
        ApplicationContext applicationContext = (ApplicationContext)servletContext.getAttribute("springContexgt");
        Object bean = applicationContext.getBean(requiredType);
        return (T)bean;
    }

}

5、Servlet的应用示例

package com.web.servlet;

import com.web.service.inf.UserService;
import com.web.util.WebContextUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/test")
public class MyServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletOutputStream outputStream = resp.getOutputStream();
        UserService userService = WebContextUtil.getApplicationContext(req.getServletContext(), UserService.class);
        outputStream.print(userService.getUserName());
    }
}
原文地址:https://www.cnblogs.com/cplinux/p/15317935.html