Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jsp

jstl

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:

enter image description here

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

like image 966
coldistric Avatar asked Oct 17 '15 05:10

coldistric


2 Answers

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

like image 144
Prince Avatar answered Oct 20 '22 13:10

Prince


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.

like image 40
JB Nizet Avatar answered Oct 20 '22 15:10

JB Nizet