Spring与Web环境集成

1.Spring与Web环境集成

1.1自定义监听器将Spring集成到web环境

1_需求:将spring集成到web开发环境中,将所有的bean对象创建交给spring,除了servlet,servlet可以理解为一个测试类.在servlet中获取ApplicationContext,获取对应的bean

环境搭建,这个是自己一步步取实现的,其实spring有提供简单的方法完成1.1的操作

<!--在pom文件中引入所需的依赖-->
    <!--Spring坐标-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <!--SpringMVC坐标-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <!--Servlet坐标-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <!--Jsp坐标-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
    </dependency>
//1.创建dao层接口和实现类
//dao接口 IUserDao
public interface IUserDao{
    void save();
}
//UserDaoImpl实现类
public class UserDaoImpl implements IUserDao{
    @Override
    public void save(){
        System.out.printLn("正在保存...");
    }
}

//2.创建service业务层接口和实现类
public interface IUserService{
    void save();
}
//UserServletImpl实现类
public class UserServiceImpl implements IUserService{
    private IUserDao userDao;
    //为依赖注入提供set方法
    public void setUserDao(IUserDao userDao){this userDao=userDao;}
    @Override
    public void save(){
        userDao.save();
    }
}
<!--applicationContext.xml文件中配置Dao,service交给spring管理-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置Dao-->
    <bean class="cn.ppvir.dao.impl.UserDaoImpl" id="userDao"></bean>

    <!--配置service-->
    <bean class="cn.ppvir.service.impl.UserServiceImpl" id="userService">
        <property name="userDao" ref="userDao"></property>
    </bean>

</beans>    
/*web包下创建UserServlet类 内部功能:调Spring容器,创建service对象,调sava()方法*/
public class UserServlet extends HttpServlet{
    @Override//复写doGet方法
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //通过配置文件获取上下文
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取bean,因为只有一个UserServiceImpl,可以使用字节码的方法获取
        UserServiceImpl userService = context.getBean(UserServiceImpl.class);
        //调用save方法
        userService.save();
    }
}
<!--在web.xml中配置 servlet-->
<servlet>
    <servlet-name>userServlet</servlet-name>
    <servlet-class>cn.ppvir.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>userServlet</servlet-name>
    <url-pattern>/userServlet</url-pattern>
</servlet-mapping>

最后配置tomcat,启动测试
http://localhost:80/userServlet

2_问题描述:
spring在web开发环境下,每个servlet都需要new ClassPathXmlApplicationContext("applicationContext.xml")
因为配置文件会加载多次,所以会造成性能浪费

3_改进一:
将ApplicationContext对象的创建交给监听器创建,监听器将创建好的对象存入ServletContext域对象中,在servlet中直接获取该对象.

  • 编写监听器代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //获取上下文
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //将spring获取到的应用上下文,保存到servletContext域中
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("context",context);
        //之后去web.xml配置listener监听器和改写servlet代码
    }
  • 监听器配置
web.xml
<!--配置servlet-->

<!--配置自己实现的监听器-->
  <listener>
    <listener-class>cn.ppvir.listener.ContextLoaderListener</listener-class>
  </listener>
  • servlet代码改写
public class UserServlet extends HttpServlet {
    /**
     * 改进一:
     * 将ApplicationContext对象的创建交给监听器创建,监听器将创建好的对象存入ServletContext域对象中,在servlet中直接取该对象即可
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取servletContext域对象
        ServletContext servletContext = this.getServletContext();
        //从ServletContext域对象中,获取监听器创建的应用上下文,强转为ApplicationContext
        ApplicationContext context = (ApplicationContext) servletContext.getAttribute("context");
        UserServiceImpl userService = context.getBean(UserServiceImpl.class);
        userService.save();
    }
}

重启tomcat完成测试.

4.优化二:

  • 1_在web.xml文件中配置要加载的applicationContext.xml文件
web.xml
<!--改进二: 之前的基础上添加配置-->
  <!--全局初始化参数-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  • 2.改写ContextLoaderListener监听器类,获取全局初始化参数
public class ContextLoaderListener implements ServletContextListener {
    /**
     * 优化二: 获取全局初始化参数
     *
     * @param servletContextEvent
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //获取域对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        //从配置文件中获取applicationContext
        /*
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
         */
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        //获取应用上下文
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(contextConfigLocation);
        //将Spring的应用上下文 存储到ServletContext域对象中
        servletContext.setAttribute("context",context);
        System.out.println("spring容器创建完毕...");
    }
}
  • 3.优化强转ApplicationContext,使用工具类直接从servletContext域对象中获取applicationContext对象.
//创建工具类
package cn.ppvir.listener;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
/**
 * 工具类,强转context上下文为ApplicationContext
 */
public class WebApplicationContextUtils {
    /**
     * @param servletContext 参数是域对象
     * @return  返回值是强转后的对象ApplicationContext
     */
    public static ApplicationContext getWebapplicationContext(ServletContext servletContext){
        return (ApplicationContext)servletContext.getAttribute("context");
    }
}
  • 4.修改UserServlet类使用WebApplicationContextUtils优化强转context
public class ContextLoaderListener implements ServletContextListener {
     /**
     * 优化二: 使用WebApplicationContextUtils工具类,简化强转上下文对象的操作
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //获取域对象
        ServletContext servletContext = this.getServletContext();
        ApplicationContext context = WebApplicationContextUtils.getWebapplicationContext(servletContext);
        UserServiceImpl userService = context.getBean(UserServiceImpl.class);
        userService.save();
    }
}

重启tomcat完成测试

1.2使用spring提供的监听器将spring集成到web环境

UserDao和UserService层与上面一样

  • 导入依赖
pom.xml
 <!--spring-web坐标-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
  • 配置Spring提供的监听器ContextLoaderListener
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">
  <!--全局参数-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--配置servlet-->
  <servlet>
    <servlet-name>service</servlet-name>
    <servlet-class>web.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>service</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
  • applicationContext.xml配置让spring管理注入
applicationContext.xml
<bean class="dao.impl.UserDaoImpl" id="userDao"></bean>

    <bean class="service.impl.UserServiceImpl" id="userService">
        <property name="userDao" ref="userDao"></property>
    </bean>
  • servlet中通过工具获得应用上下文对象
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取servletContext域对象
        ServletContext servletContext = this.getServletContext();
        //使用spring框架自带的WebApplicationContextUtils工具,获取上下文对象
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserServiceImpl userService = context.getBean(UserServiceImpl.class);
        userService.save();
    }
}

1.3小结:

1.web环境中集成spring只需要配置监听器即可
2.Spring负责管理处=除了controller以外的所有bean对象

原文地址:https://www.cnblogs.com/ppvir/p/11403064.html

时间: 2024-08-25 14:32:35

Spring与Web环境集成的相关文章

Spring-IOC 在非 web 环境下优雅关闭容器

当我们设计一个程序时,依赖了Spring容器,然而并不需要spring的web环境时(Spring web环境已经提供了优雅关闭),即程序启动只需要启动Spring ApplicationContext即可,那我们如何去进行优雅关闭呢? 设计一个代理程序,仅需要Spring容器管理部分bean并启动即可.该工程最终打成一个可执行Jar包,并构建成docker镜像后进行启动 public class Main { public static void main(String[] args) thr

Shiro集成web环境[Springboot]-基础使用

Shiro集成web环境[Springboot] 1.shiro官网查找依赖的jar,其中shiro-ehcache做授权缓存时使用,另外还需要导入ehcache的jar包 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.3.2</version> </dependency&

apacheFtpServer集成spring由web容器控制启动和关闭

ApacheFtpServer是一个100%纯Java实现的FTP服务器,基于网络框架apache MINA实现,可支撑多并发用户.FtpServer可以独立运行作为一个Windows服务或Unix/Linux守护进程,或嵌入到Java应用程序,提供对内部集成spring应用程序支持.下面介绍apacheFtpServer与spring集成,交由spring控制ApacheFtpServer的启动与关闭. 1.      初始化创建MyFtpServer: import java.io.File

《Spring技术内幕》笔记-第四章 Spring MVC与web环境

?上下文在web容器中的启动 1,IoC容器的启动过程 IoC的启动过程就是建立上下文的过程,该上下文是与ServletContext相伴.在Spring中存在一个核心控制分发器,DispatcherServlet,这是Spring的核心.在web容器启动Spring应用程序时,首先建立根上下文,然后ContextLoader建立WebApplicationContext. Web容器中启动Spring过程如下: 在web.xml中,已经配置了ContextLoadListener,该类实现了S

Spring与其他Web框架集成

Spring与多种流行Web应用框架(Struts.JSF和DWR)集成的方法. Spring强大的IoC容器和企业支持特性使其十分适于实现Java EE应用的服务和持续层. 对于表现层,可以在许多不同的Web框架中选择,所以常常需要将Spring与使用中的Web框架集成. 这里的集成关注这些框架中对Spring IoC容器中声明的Bean访问. 第一节:在一般的Web应用中访问Spring 第二节:在Servlet和过滤器中使用Spring 第三节:将Spring和Struts1.x集成 第四

SpringBoot | 第三十三章:Spring web Servcies集成和使用

前言 最近有个单位内网系统需要对接统一门户,进行单点登录和待办事项对接功能.一般上政府系统都会要求做统一登录功能,这个没啥问题,反正业务系统都是做单点登录的,改下shiro相关类就好了.看了接入方案,做坑爹的是需要业务系统提供一个webService服务,供统一平台调用.对于ws服务,是真的除了大学期间要去写个调用天气预报的作业后,就再也没有接触过了.查阅了SpringBoot文档后,发现确实有一章节是将webService的,所以,今天就来简单介绍下Spring Web Service的集成和

Shiro集成web环境[Springboot]-认证与授权

Shiro集成web环境[Springboot]--认证与授权 在登录页面提交登陆数据后,发起请求也被ShiroFilter拦截,状态码为302 <form action="${pageContext.request.contextPath}/user/login" method="post"> Username:<input type="text" name="username"></br>

Spring+Spring MVC+Hibernate环境搭配

Spring+Spring MVC+Hibernate简称"SSH".Spring容器是Spring的核心,该 容器负责管理spring中的java组件.Spring的核心机制:依赖注入.Hibernate是一个不错的ORM(关系对象映射)框架.Spring+Spring MVC+Hibernate环境搭配步骤: 1.搭建Spring+Hibernate环境(跟ssh搭建步骤一致) (1)加入Spring+Hibernate的架包. 2.搭建SpringMVC环境( 1)添加Sprin

Java EE 学习(5):IDEA + maven + spring 搭建 web(1)

参考:http://www.cnblogs.com/lonelyxmas/p/5397422.html http://www.ctolib.com/docs-IntelliJ-IDEA-c--159047.html 孔老师的<SpringMVC视频教程> 记录: 本节主要完成 使用 maven 管理 spring + 项目 包,搭建 maven+spring 的 web 项目平台. 前提: 已安装并配置好 - Intellij IDEA 16.3.5 Ultimate - JDK 1.8.0_