BAEL-6670: Reading a JSP variable from JavaScript (#14337)

This commit is contained in:
Manfred
2023-07-09 04:24:38 +01:00
committed by GitHub
parent 6fa3c122e3
commit ba1764fba1
6 changed files with 114 additions and 0 deletions
@@ -0,0 +1,31 @@
package com.baeldung.boot.jsp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/jsp-var")
public class JSPVariableController {
@GetMapping("/by-jsp")
public String byJsp() {
return "/jsp-var/by-jsp";
}
@GetMapping("/by-el")
public String byEl() {
return "/jsp-var/by-el";
}
@GetMapping("/by-jstl")
public String byJstl() {
return "/jsp-var/by-jstl";
}
@GetMapping("/to-dom")
public String byDom() {
return "/jsp-var/to-dom";
}
}
@@ -0,0 +1,18 @@
<%@ page import="org.apache.commons.text.StringEscapeUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String jspMsg = StringEscapeUtils.escapeEcmaScript("Hello! This is Sam's page.");
request.setAttribute("jspMsg", jspMsg);
%>
<html>
<head>
<title>Conversion by JSP EL</title>
<script type="text/javascript">
var jsMsg = '${requestScope.jspMsg}';
console.info(jsMsg);
</script>
</head>
<body>
<div>Open the browser console to see the message.</div>
</body>
</html>
@@ -0,0 +1,16 @@
<%@ page import="org.apache.commons.text.StringEscapeUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String jspMsg = StringEscapeUtils.escapeEcmaScript("Hello! This is Sam's page.");
%>
<html>
<head>
<title>Conversion by JSP expression tag</title>
var jsMsg = '<%=jspMsg%>';
console.info(jsMsg);
</script>
</head>
<body>
<div>Open the browser console to see the message.</div>
</body>
</html>
@@ -0,0 +1,19 @@
<%@ page import="org.apache.commons.text.StringEscapeUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String jspMsg = StringEscapeUtils.escapeEcmaScript("Hello! This is Sam's page.");
request.setAttribute("scopedMsg", jspMsg);
%>
<html>
<head>
<title>Conversion by JSTL</title>
<script type="text/javascript">
var jsMsg = '<c:out value="${scopedMsg}" escapeXml="false"/>';
console.info(jsMsg);
</script>
</head>
<body>
<div>Open the browser console to see the message.</div>
</body>
</html>
@@ -0,0 +1,19 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String jspTag = "<h1>Hello</h1>";
%>
<html>
<head>
<title>Convert to an HTML tag</title>
<script type="text/javascript">
function printTag() {
var tags = document.getElementById("fromJspTag").innerHTML;
console.info(tags);
}
</script>
</head>
<body onLoad="printTag()">
<div id="fromJspTag"><%=jspTag%></div>
<div>Open the browser console to see the tags.</div>
</body>
</html>