与其他spring文件不同的是,运用request的spring不需要再src建立bean.xml文件,只需在web.xml文件同目录下建立一个application.xml文件
3. request:对于一次HTTP请求,request作用域只产生一个Bean实例,请求结束时Bean实例将会销毁。也就说两次login请求,将会产生两个userBean。每一次login请求多次调用userBean会得到同一个实例。只有在Web应用中使用Spring时,该作用域才有效。
4. session:对于一次HTTP会话,session作用域只产生一个Bean实例,session销毁时Bean实例将会销毁。也就是说用户A和用户B都请求了查询操作,将会产生两个queryBean实例。A用户多个请求查询操作,将会产生一个queryBean实例。只有在Web应用中使用Spring时,该作用域才有效。
5. global session:每个全局的HTTP session对应一个bean实例。在典型的情况下,仅在使用porlet context的时候才有效。只有在Web应用中使用Spring时,该作用域才有效。(可以了理解成jsp的application内置对象作用范围)
并且它是需要写视图层的 也就是JSP
具体代码如下:
测试层:
配置文件application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="p" class="com.cn.Person"
scope="request"/>
</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" 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>SpringRequestDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>
jsp文件:
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="org.springframework.web.context.*" %>
<%@ page import="org.springframework.web.context.support.*" %>
<%@ page import="com.cn.Person"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Spring Bean的作用域</title>
</head>
<body>
<%
// 获取Web应用初始化的Spring容器
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(application);
// 两次获取容器中id为p的Bean
Person p1 = (Person)ctx.getBean("p");
Person p2 = (Person)ctx.getBean("p");
out.println((p1 == p2) + "<br/>");
out.println(p1);
out.println(p2);
%>
</body>
</html>