Fork me on GitHub

spring之如何在web应用中使用?

1.需要引入额外的jar包:

  • spring-web
  • spring-webmvc

2.spring的配置文件没什么区别。

3.如何创建IOC容器?

  • 非web应用在main方法中直接创建;
  • 在web应用中应该在被服务器加载时就创建;
  • 在ServletContextListener#contextInitialized(ServletContextEvent sce)方法中创建IOC容器;

4.在WEB应用中其它组件如何来访问IOC容器呢?

可以将IOC容器放在ServletContext(即applicaiton域)的一个属性中。

5.实际上spring配置文件的名字和位置也是可以配置的。将其配置到当前web应用的初始化参数中较为合适。

实际操作:

新建一个动态的java web项目

需要注意的是不要直接按finish,要一直到最后将web.xml文件导入进来。

将相关的java包放入到WEB-INF的lib下。

相关目录如下:

Person.java

package com.gong.spring.struts2.beans;

public class Person {
    
    private String username;
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public void hello(){
        System.out.println("My name is " + username);
    }
    
}

SpringServletContextListener.java

package com.gong.spring.struts2.listeners;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Application Lifecycle Listener implementation class SpringServletContextListener
 *
 */
@WebListener
public class SpringServletContextListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public SpringServletContextListener() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
        // TODO Auto-generated method stub
        //1.获取spring配置文件的名称
        ServletContext servletContext = arg0.getServletContext();
        String config = servletContext.getInitParameter("contextConfigLocation");
        //2..创建IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        //3.将IOC容器放在ServletContext的一个属性中
        servletContext.setAttribute("ApplicationContext", ctx);
    }
    
}

TestServlet.java

package com.gong.spring.struts2.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 com.gong.spring.struts2.beans.Person;

/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 从 application 域对象中得到 IOC 容器的引用
        ServletContext servletContext = getServletContext();
        ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
        
        //2. 从 IOC 容器中得到需要的 bean
        Person person = ctx.getBean(Person.class);
        person.hello();
    }

}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person"
        class="com.gong.spring.struts2.beans.Person">
        <property name="username" value="gong"></property>
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>ssm</display-name>

    <!-- 加载springIOC容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>applicationContext.xml</param-value>
    </context-param>
    <!-- 启动IOC容器的ServletContextListener -->
    <listener>
        <listener-class>com.gong.spring.struts2.listeners.SpringServletContextListener</listener-class>
    </listener>
    <servlet>
        <description></description>
        <display-name>TestServlet</display-name>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>com.gong.spring.struts2.servlets.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <a href="TestServlet">TestServlet</a>
    
</body>
</html>

启动tomcat服务器之后,访问http://localhost:8080/myspring5/index.jsp

点击:

在终端输出:

说明在WEB应用中配置和使用springIOC容器是成功的。 

posted @ 2020-01-09 17:35  西西嘛呦  阅读(678)  评论(0编辑  收藏  举报