spring-application in web

Using Spring in a Web Environment

①. Additional jar packages that need to be added:

spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

②. Spring's configuration file is no different from a non-WEB environment

③. The following configuration needs to be added to the web.xml file:

<!-- Configure the name and location of the Spring configuration file-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</ context-param>

<!-- 启动 IOC 容器的 ServletContextListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

    <!-- Configure the name and location of the Spring configuration file --> 
    < context-param > 
        < param-name > contextConfigLocation </ param-name > 
        < param-value > classpath:applicationContext.xml </ param-value > 
    </ context-param >
    
    <!-- 启动 IOC 容器的 ServletContextListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 配置 Struts2 的 Filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

text.jsp:

<body>
    
    <%  
        // 1. Get the instance of the IOC container from the application domain object
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);
        
        // 2. Get the bean from the IOC container
        Person person = ctx.getBean(Person.class);
        
        // 3. Use beans
        person.hello();
    %>
    
</body>

Configuration file:

<?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.atguigu.spring.struts2.beans.Person">
        <property name="username" value="spring"></property>    
    </bean>
    
</beans>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324770671&siteId=291194637