You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将<jsp:setProperty>的值设为脚本段声明的字符串变量?

回答:可以将脚本段变量赋值给<jsp:setProperty>的value属性

当然没问题!你完全可以把之前在脚本段里声明的type变量赋值给<jsp:setProperty>的value属性,不过得用正确的语法引用这个变量——你当前代码里的value=""是空值,肯定达不到预期效果。下面给你两种可行的写法:

方法1:使用JSP表达式(<%= %>)

这是比较传统的写法,直接把变量嵌入到属性值中:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<% String type = request.getParameter("type"); %> 
<title><% out.println(type);%> </title> 
</head> 
<jsp:useBean id="myBean" scope="session" class="org.geeks.Second"/> 
<jsp:setProperty name="myBean" property="type" value="<%= type %>"/>

方法2:使用EL表达式(${})

这是更推荐的现代写法,代码简洁易读,只要变量在当前作用域内就能直接引用:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<% String type = request.getParameter("type"); %> 
<title>${type}</title> 
</head> 
<jsp:useBean id="myBean" scope="session" class="org.geeks.Second"/> 
<jsp:setProperty name="myBean" property="type" value="${type}"/>

注意点:

  • 如果你用EL表达式,要确保你的Web容器支持JSP 2.0及以上版本(现在主流容器都满足这个条件)。
  • 脚本段里声明的type变量属于页面作用域,所以EL可以直接通过${type}访问到。

内容的提问来源于stack exchange,提问作者Jack Gads

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:07:53