How to use JSP tags in JavaScript

        In the face of "ancient" projects, it is very difficult to extend their life and maximize their value. How to use JSP tags in JS? How to make ES6 template strings contain JSP tags, EL expressions, and JS variables to be recognized normally? How to solve the syntax conflict between JSP's EL expression and ES6 template string? This article sorts out several difficulties encountered, and analyzes them in depth in combination with actual cases.

Table of contents

1. Brief introduction

1.1, JSP EL expression

1.2, JavaScript ES6 template string

2. Case Analysis

2.1, JavaScript script naming

2.2. Configuration file suffix name mapping

2.3. Insert JSP tags into JS scripts

2.4. Introducing custom JS scripts into JSP

3. Practice summary


Operating environment:

1. Brief introduction

        This case is a Java project, the infrastructure is Spring MVC, and the technical points used are: JSP EL expressions, ES6 template strings, JSP tags, etc.

1.1, JSP EL expression

        EL ( Expression Language ) accesses model objects in JSP through the syntax of EL expressions .

Variable: ${  variable name  }
Operation: ${  not empty variable name? variable name: "default value"  }

1.2, JavaScript ES6 template string

        In the traditional JavaScript language, the output template is usually a concatenation of strings and variables, which may involve escaping, and the writing method is quite cumbersome and inconvenient. Using  ES6 template strings  (backtick ` ) perfectly solves this problem. as follows:

let unitPrice = 1.68;

// 传统写法
alert('<div>单价:<em>' + unitPrice + '</em> 元</div>');
 
// 模板字符串,换行、空格、缩进均会保留
alert(`<div>单价:<em>${unitPrice}</em> 元</div>`);

2. Case Analysis

        How to use JSP tags in JavaScript, the following will be analyzed in detail.

2.1, JavaScript script naming

Usually, the         JavaScript script file is named  XXX.js , and to enable the JSP engine to parse the JSP code in JS, you first need to change the file extension to XXX.jsp .

        In this case, the customized JS script is named XXX . js . jsp to distinguish it from the standard JSP file , such as: JS script . js . jsp containing JSP tags

2.2. Configuration file suffix name mapping

        In order for the JSP engine to interpret the JSP tags of JS scripts normally, it is necessary to configure servlet-mapping in "xxx-gateway/src/main/webapp/WEB-INF/web.xml" in the root directory of the project, and for JS scripts containing JSP codes File mapping (note: wildcards are allowed for fuzzy matching). as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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-app_3_1.xsd"
         version="3.1" >
	<display-name>Admin Web</display-name>

	<!-- WebAppRootKey -->
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>admin-gateway</param-value>
	</context-param>
	
	<context-param>
        <param-name>isLog4jAutoInitializationDisabled</param-name>
        <param-value>true</param-value>
    </context-param>

    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <!-- JavaScript文件中使用的 JSP标签 由服务端来解释 -->
        <url-pattern>/static/js/含有JSP标签的JS脚本.js.jsp</url-pattern>
    </servlet-mapping>

	<!-- Error page -->
	<!--
	<error-page>
		<exception-type>java.lang.Throwable</exception-type>
		<location>/WEB-INF/views/error/500.jsp</location>
	</error-page>
	-->
	<error-page>
		<error-code>500</error-code>
		<location>/WEB-INF/views/error/500.jsp</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/WEB-INF/views/error/404.jsp</location>
	</error-page>
</web-app>

2.3. Use JSP tags in JS scripts

It mainly includes the following technical points:

  • Before JSP rendering, you need to declare the character set first to avoid Chinese garbled characters;
  • In the JS script, import the JSP custom tag library;
  • When the ES6 template string in the JS script contains JSP tags, EL expressions, and JS variables mixed nesting, the JS variable is passed as a parameter to the internal call of the JSP tag, and the format of ${ ' ${ JS variable name } ' } needs to be used ;

The content of the script file " JS Script.js.jsp Containing JSP Tags " is as follows:

<%-- 指定页面字符集:解决 JavaScript 文件中使用 ES6模板字符串 渲染页面时乱码 --%>
<%@ page contentType="text/javascript;charset=UTF-8" %>
<%-- 导入JSP自定义标签库:解决 JavaScript 文件中使用 ES6模板字符串 无法解析JSP标签 --%>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>

// TODO 此处省略1万字

// ES6模板字符串 含有 JSP标签、EL表达式、JS变量
let userNo = '123456';
console.log(`<sys:user id="${'${userNo}'}">`);

// TODO 此处省略1万字

Notice:

1. Using ${} in a JSP file will be prioritized as an EL expression instead of a JS ES6 template string;

2. If the JSP tag contains HTML string value splicing, you need to use single  quotes '  instead, otherwise, after the ES6 template string is parsed, a string splicing exception will be reported;

2.4. Introducing custom JS scripts into JSP

        The content of the JSP page file accessed by the user is as follows:

<html>
<head>
<title>JS脚本中插入JSP标签Demo</title>
<script src="/static/js/含有JSP标签的JS脚本.js.jsp"></script>
<script type="text/javascript">
    // TODO
</script>
</head>
<body>
正文
</body>
</html>

3. Practice summary

The technical points encountered in this case were finally processed step by step by the reverse method, which took a lot of effort. as follows:

  • JSP engine parses JS script
  • The parsed JS script is garbled
  • How to make JS recognize JSP tags normally
  • ES6 template strings inserted into JS variables
  • JSP EL expression and JS ES6 template string syntax conflict resolution

appendix:

I hope it can help code friends. If you encounter other problems, please leave a message and discuss...

Guess you like

Origin blog.csdn.net/Sn_Keys/article/details/129590697