簡體   English   中英

如何縮短自定義 JSP 標簽生成的 output?

[英]How to shorten output generated by custom JSP tag?

是否可以使我自己的 JSP 標簽生成的 output 更短? 例如,定義如下的標記生成 5 行而不是 1 行。是否可以避免這種情況(沒有將所有 5 行加入標記源中的 1 行)?

<%@ tag description="link" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ attribute name="href" required="true" type="java.lang.String" %>
<%@ attribute name="label" required="false" type="java.lang.String" %>
<a href="<c:url value="${href}"/>">${not empty label ? label : href}</a>

不是解決方案:

<%@ tag description="standard input" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ attribute name="href" required="true" type="java.lang.String" description="address relative to web-app context" %><%@ attribute name="label" required="false" type="java.lang.String" description="link label" %><a href="<c:url value="${href}"/>">${not empty label ? label : href}</a>

正如 werkshy 已經指出的那樣,為了避免 JSP 自定義標簽中使用的指令生成空格,

<%@ tag trimDirectiveWhitespaces="true" %>

可以使用(<%@ page trimDirectiveWhitespaces="true" %> 在這種情況下沒有幫助,因為它似乎只適用於 JSP 本身的指令,而不適用於頁面使用的自定義標簽)。

However, to allow this tag attribute, JSP version 2.1 might need to be specified eg using an implicit.tld (as described on https://docs.oracle.com/javaee/5/tutorial/doc/bnamu.html or https: //forums.oracle.com/thread/742224 )然后需要將其放入帶有標簽的目錄中。 (至少我需要為 WebLogic 12c 這樣做。)

隱式.tld:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
    <tlib-version>1.0</tlib-version>
    <short-name>implicit</short-name>
</taglib>

是的,您可以全局配置 JSP 解析器來修剪腳本表達式和標簽留下的空白。

將此添加到您的 webapp 的web.xml (必須與 Servlet 2.5 兼容:):

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <trim-directive-whitespaces>true</trim-directive-whitespaces>
    </jsp-property-group>
</jsp-config>

如果您的目標是 Servlet 2.4 容器或更低版本,那么您必須編輯容器自己的web.xml來全局應用它。 例如,在 Tomcat 中,它是/conf/web.xml文件。 搜索JspServlet<servlet>聲明,並在<servlet> servlet> 聲明中添加以下 servlet init 參數。

<init-param>
    <param-name>trimSpaces</param-name>
    <param-value>true</param-value>
</init-param>

在您的 JSP 中:

<%@ page trimDirectiveWhitespaces="true" %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM