栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在JSP中访问常量(没有scriptlet)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在JSP中访问常量(没有scriptlet)

它在您的示例中不起作用,因为该

ATTR_CURRENT_USER
常量对于JSTL标记不可见,因为JSTL标记期望属性由getter函数公开。我还没有尝试过,但是暴露常量的最干净的方法似乎是非标准标记库。

ETA:我给的旧链接无效。在此答案中可以找到新的链接:

代码段来阐明您所看到的行为:示例类:

package com.example;public class Constants{    // attribute, visible to the scriptlet    public static final String ATTR_CURRENT_USER = "current.user";    // getter function;    // name modified to make it clear, later on,     // that I am calling this function    // and not accessing the constant    public String getATTR_CURRENT_USER_FUNC()    {        return ATTR_CURRENT_USER;    }}

JSP页面的片段,显示示例用法:

<%-- Set up the current user --%><%    session.setAttribute("current.user", "Me");%><%-- scriptlets --%><%@ page import="com.example.Constants" %><h1>Using scriptlets</h1><h3>Constants.ATTR_CURRENT_USER</h3><%=Constants.ATTR_CURRENT_USER%> <br /><h3>Session[Constants.ATTR_CURRENT_USER]</h3><%=session.getAttribute(Constants.ATTR_CURRENT_USER)%><%-- JSTL --%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><jsp:useBean id="cons"  scope="session"/><h1>Using JSTL</h1><h3>Constants.getATTR_CURRENT_USER_FUNC()</h3><c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/><h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3><c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/><h3>Constants.ATTR_CURRENT_USER</h3><c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/><%--Commented out, because otherwise will error:The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.<h3>cons.ATTR_CURRENT_USER</h3><c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>--%><hr />

输出:

使用脚本

常数.ATTR_CURRENT_USER

当前用户

会话[Constants.ATTR_CURRENT_USER]


使用JSTL

Constants.getATTR_CURRENT_USER_FUNC()

当前用户

会话[Constants.getATTR_CURRENT_USER_FUNC()]

常数.ATTR_CURRENT_USER




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号