1.在核心包基础上引入下面两个jar包。
spring-web-4.2.6.RELEASE.jarspring-webmvc-4.2.6.RELEASE.jar
2.配置文件和非web得xml配置文件相同。
3.在Web中使用的原理
IoC容器创建时机:ServletContextListener被初始化时创建。在整合其他框架比如Struts2时,可以将Ioc容器,放在ServletContext的一个属性中。
这样,整个WebApplication都可以使用到IoC来获取数据啦。
Spring内部就是按照这个方法来实现的。
4.通过Spring封装的Listener来加载IoC容器
5.具体代码实现步骤
1)编写Person Bean类
实现比较简单这里省略。
2)在Java Resources的Src目录下添加springContextConfig.xml配置文件。并配置person的Bean。
<?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="spring.Person">
<property name="name" value="high"></property>
<property name="age" value="20"></property>
</bean>
</beans>
3)步骤1、2就是基本的spring使用步骤,跟之前的一致。接下来配置web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置Spring配置文件的名称和位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springContextConfig.xml</param-value>
</context-param>
<!-- 启动Ioc容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
4)编写jsp文件测试
<%@page import="spring.Person"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@ 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>
<%
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);
Person person = ctx.getBean("person", Person.class);
out.println(person);
%>
</body>
</html>
<完>