Spring Bean转Class后传递至JSP获取值为空的问题求助
问题分析与解决方案
你遇到的问题核心在于JSP的<jsp:useBean>和Spring容器是完全独立的两个体系,导致你拿到的不是Spring初始化的那个Bean,而是一个全新的未赋值实例,所以所有属性都是null。
为什么会拿到null?
<jsp:useBean>是JSP的标准动作,它的逻辑是:
- 在指定的作用域(这里是
application)里查找id为propertyData的对象; - 如果找不到,直接调用
utils.PropertyDataFill的无参构造器创建一个新对象,并放到application作用域中。
而你在Spring里配置的propertyData Bean,是存放在Spring自己的ApplicationContext容器里的,并没有自动放到ServletContext(对应JSP的application作用域)中。所以<jsp:useBean>找不到现成的对象,就新建了一个属性全为null的实例,这就是你拿到null的原因。
解决方法
方法1:把Spring Bean同步到ServletContext(application作用域)
可以通过Spring提供的ServletContextAttributeExporter,把Spring管理的Bean手动注入到ServletContext中。在你的Spring配置文件里添加:
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter"> <property name="attributes"> <map> <!-- 把Spring里的propertyData Bean映射到ServletContext的propertyData属性 --> <entry key="propertyData" value-ref="propertyData"/> </map> </property> </bean>
配置完成后,Spring启动时会自动把propertyData Bean放到application作用域,此时<jsp:useBean>就能找到正确的实例,调用getter就能拿到属性值了。
方法2:直接从Spring容器中获取Bean(无需修改Spring配置)
在JSP里通过Spring的工具类直接获取WebApplicationContext,再从中取出Bean:
<% // 获取Spring的Web应用上下文 org.springframework.web.context.WebApplicationContext ctx = org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext()); // 从容器中拿到propertyData Bean utils.PropertyDataFill propertyData = (utils.PropertyDataFill) ctx.getBean("propertyData"); // 现在就能拿到正确的属性值了 String m = propertyData.getIsActiveM(); String u = propertyData.getIsActiveU(); String g = propertyData.getIsActiveG(); %>
方法3:使用Spring JSP标签库(推荐,更优雅)
如果不想用Scriptlet(<% %>),可以用Spring提供的JSP标签库来获取Bean或属性,代码更简洁。
首先在JSP头部引入Spring标签库:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
然后可以直接获取Bean,或者直接提取属性:
<!-- 获取Bean到页面变量 --> <spring:bean id="propertyData" name="propertyData" scope="application"/> <!-- 或者直接把属性赋值给页面变量,无需手动调用getter --> <spring:eval var="m" expression="@propertyData.isActiveM"/> <spring:eval var="u" expression="@propertyData.isActiveU"/> <spring:eval var="g" expression="@propertyData.isActiveG"/>
额外注意事项
- 确保你的Spring配置文件已经被Web应用正确加载:比如在
web.xml中配置了ContextLoaderListener,否则Spring容器根本没初始化,Bean自然不存在。 - 检查属性占位符是否生效:你的Bean属性用了
${current}这类占位符,要确保Spring配置了PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer,否则Spring无法解析这些占位符,Bean的属性本身就是null,即使拿到Bean也会返回null。
内容的提问来源于stack exchange,提问作者Insanity Geek
相关产品推荐
相关产品推荐

