How to print a java String in a jsp file [duplicate]

跟風遠走 提交于 2019-12-22 08:29:19

问题


I'm trying to print a string variable via my jsp file, here is my code:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.lang.*;"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<!DOCTYPE html>

<html>
<head>
<title>why are you not working</title>
<meta charset="utf-8" />
</head>

<body>
    <%
        String test = "<b><u>bold and underlined</u></b>";
     %>

    <c:set var="test1" value="<u>underlined</u>" />
    <c:set var="test2" value="${test}" />

    <c:out value="${test}" escapeXml="false" />
    <c:out value="${test1}" escapeXml="false" />
    <c:out value="${test2}" escapeXml="false" />

</body>
</html>

output:

Is there a way to print test or test2 using JSTL ? As you can see in the code above I've managed to print the variable test1 but nothing appear on the page for the variables test or test2.

PS: why I want to use JSTL ? Because it offers a way to evaluate html tags and not escape them


回答1:


yes there is.You can set your variable test in page scope using pageContext object.

<body>
    <%
        String test = "<b><u>bold and underlined</u></b>";
        pageContext.setAttribute("test", test);
     %>

    <c:set var="test1" value="<u>underlined</u>" />
    <c:set var="test2" value="${test}" />

    <c:out value="${test}" escapeXml="false" />
    <c:out value="${test1}" escapeXml="false" />
    <c:out value="${test2}" escapeXml="false" />

</body>

Output

bold and underlined underlined bold and underlined

JSTL works entirely with scoped variables where scope can be request,session or page.By default scope is page. While scriplet is raw java which is inserted into the service method of the JSP page’s servlet. So if you want to access any scriplet variable in JSTL,you need to set in scope.

See Also

  • I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error



回答2:


The JSP EL "variables" are not local variables. When you write

${test}

the JSP EL looks for an attribute named "test", in the page scope, or in the request scope, or in the session scope, or in the application scope.

So, it's basically equivalent to the following Java code:

<%= out.print(pageContext.findAttribute("test")); %>

You can't access a local variable as you're trying to do with the JSP EL. And there's no reasong to want to, because you shouldn't have Java code (i.e. scriptlets) in the JSP anyway. The controller, written in Java, should store attributes in the request, and the JSP EL should display the values stored in those attributes.



来源:https://stackoverflow.com/questions/33183108/how-to-print-a-java-string-in-a-jsp-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!