【问题标题】:Is it possible to get page context within JSTL custom tag doTag()?是否可以在 JSTL 自定义标签 doTag() 中获取页面上下文?
【发布时间】:2013-01-14 10:21:39
【问题描述】:

我只是一个初学者,正在开发我的第一个网络应用程序。我正在尝试支持多种语言,因此我在我的 JSTL 自定义标记逻辑的主体中使用基于包的消息。像这样:

ResourceBundle rs = ResourceBundle.getBundle("i18n.messages");

JspWriter out = getJspContext().getOut();
try {


out.print("<table><thead>");
        out.print("<th>"+ rs.getString("table.id") +"</th>");
        out.print("<th>"+ rs.getString("table.name") +"</th>");
        out.print("<th>"+ rs.getString("table.entry") +"</th>");
        out.print("<th>"+ rs.getString("table.diagnosis") +"</th>");
        out.print("<th>"+ rs.getString("table.doctor") +"</th>");
        out.print("<th>"+ rs.getString("table.release") +"</th>");
        out.print("</thead><tbody>");

问题是 - 我找不到任何可能为这个捆绑包设置一个区域设置而不声明一个多余的标签属性。有点:

<attribute>
  <name>locale</name>
  <required>true</required>
  <rtexprvalue>true</rtexprvalue>
  <type>java.lang.String</type>
</attribute>

然后:

<table:patients locale="${pageContext.request.locale}" />

但它似乎工作不正确,总是传递相同的语言环境字符串(默认到我的浏览器???),与我在标题中设置的内容无关

<fmt:setLocale value="${param.locale}" scope="session"/>

有没有什么聪明的方法可以在 doTag() 正文中获取会话上下文?

提前致谢。

【问题讨论】:

    标签: web-applications jstl custom-tags


    【解决方案1】:

    JSTL 还提供了一个可能有用的Java API,但您需要实现Tag 接口(不是SimpleTag),因为您需要一种方法来获取PageContext 实例。假设您正在扩展 TagSupport,请尝试以下操作:

    import javax.servlet.jsp.jstl.fmt.LocaleSupport;
    
        public int doEndTag() throws JspException {
            //...
            String tableId = LocaleSupport.getLocalizedMessage(this.pageContext, "table.id", "i18n.messages");
            //...
            return EVAL_PAGE;
        }
    

    【讨论】:

      【解决方案2】:

      您可以使用 SimpleTagSupport 访问 JSTL 自定义标签实现中的请求、响应、会话和其他对象:

      class MyCustomTag extends SimpleTagSupport {
          @Override
          public void doTag() throws JspException, IOException {
              final PageContext pageContext = (PageContext) getJspContext();
              final ServletRequest request = pageContext.getRequest();
              final ServletResponse response = pageContext.getResponse();
              final HttpSession session = pageContext.getSession();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-15
        • 2016-01-30
        • 1970-01-01
        • 2019-10-22
        • 2013-01-14
        • 1970-01-01
        相关资源
        最近更新 更多