如何缩短自定义JSP标记生成的输出?

mar*_*osh 12 java jsp

是否可以使我自己的JSP标记生成的输出更短?例如,定义如下的标签生成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>
Run Code Online (Sandbox Code Playgroud)

不是解决方案:

<%@ 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>
Run Code Online (Sandbox Code Playgroud)

anr*_*nre 16

正如werkshy已经指出的那样,为了避免JSP自定义标记中使用的指令生成空格,

<%@ tag trimDirectiveWhitespaces="true" %>
Run Code Online (Sandbox Code Playgroud)

可以使用(<%@ page trimDirectiveWhitespaces ="true"%>在这种情况下没有帮助,因为它似乎只适用于JSP本身的指令而不适用于页面使用的自定义标记).

但是,要允许此标记属性,可能需要指定JSP版本2.1,例如使用implicit.tld(如https://docs.oracle.com/javaee/5/tutorial/doc/bnamu.htmlhttps所述: //forums.oracle.com/thread/742224)然后需要将其放入带有标签的目录中.(至少我需要为WebLogic 12c做到这一点.)

implicit.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>
Run Code Online (Sandbox Code Playgroud)


Bal*_*usC 7

是的,您可以全局配置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>
Run Code Online (Sandbox Code Playgroud)

如果您定位Servlet 2.4容器或更低容器,则必须编辑容器自己web.xml而不是全局应用它.例如,在Tomcat中,它就是/conf/web.xml文件.搜索<servlet>声明JspServlet并在声明中添加以下servlet init参数<servlet>.

<init-param>
    <param-name>trimSpaces</param-name>
    <param-value>true</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)

  • `<trim-directive-whitespaces>`仅适用于.jsp页面(与`<%@ page trimDirectiveWhitespaces ="true"%>`相同),但不适用于我自己的标签生成输出.只有`trimSpaces`作为init param才能工作并获得我的标签的1行输出. (2认同)