ferz
ferz

Reputation: 503

How to transfer String from Servlet to JSP?

servlet file

String str = req.getParameter("str");
req.setAttribute("str", "java");
getServletContext().getRequestDispatcher("/us.jsp").forward(req, resp);

jsp file

<jsp:useBean id="str" class="hws" scope="request">

or

<div align="center">
    <textarea readonly name="" cols="50" rows="25"><%= request.getAttribute("str") %></ textarea>
</div>
<form action="/us" method="post">
    <div align="center">
        <textarea name="str" cols="50" rows="3">welcome to my program</textarea>
    </div>
</form>

Upvotes: 3

Views: 3220

Answers (2)

BalusC
BalusC

Reputation: 1109874

Use EL (Expression Language, those ${} things). It has implicit access to request/session/application scoped attributes by just its attribute name.

<textarea readonly>${str}</textarea>

Be careful with XSS though whenever it concerns user-controlled input.

See also:

Upvotes: 4

user147373
user147373

Reputation:

While BalusC is correct, I wanted to point out the potential security risk with directly outputting a string. According to the Java Servlet 2.0 spec,

In cases where escaping is desired (for example, to help prevent cross-site scripting attacks), the JSTL core tag can be used.

For example:

<c:out value=”${anELexpression}” />

This can help protected against XSS attacks. See the OWASP page for more info.

Upvotes: 4

Related Questions