Spring-整合Web

1.在核心包基础上引入下面两个jar包。
spring-web-4.2.6.RELEASE.jar
spring-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>
<完>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值