简体   繁体   English

如何将Java字符串传递给JSP-标题搜索结果

[英]How to pass a Java String to JSP - to title search results

I have a JSP page with Java searching a local eXist DB. 我有一个Java搜索本地eXist DB的JSP页面。 I am looking to pass the value of a Java String to a <div> tag in the JSP. 我希望将Java字符串的值传递给JSP中的<div>标记。

I want to do this so that the title of my results container reflects what the user has searched for. 我想这样做,以便结果容器的标题反映用户搜索的内容。

eg “Your search for containerTitle has returned 9 matches” 例如:“您对containerTitle搜索已返回9个匹配项”

My Code 我的密码

<div class='concept-container result-container'>
<ul class="menu menu-style">
 <li>
    <a href="javascript:;">Concept Bar</a>
    <ul>
        <div id="title">Concept Title</div>
<%

    String containerTitle = userSearchQuery;

I am looking to change either Concept Bar or Concept Title into containerTitle. 我想将Concept Bar或Concept Title更改为containerTitle。 (which stores the string the user has searched for. (存储用户搜索的字符串。

Any help is much appriciated. 任何帮助都非常有用。

Use the setAttribute method on HTTPServletRequest . HTTPServletRequest上使用setAttribute方法。 Then you can either say request.getAttribute in the Java code embedded on your JSP page or use request.foo to read an attribute called foo in the JSP Expression Language. 然后,您可以在JSP页面上嵌入的Java代码中说出request.getAttribute ,或者使用request.foo来读取JSP表达式语言中称为foo的属性。

If you just want to print the value of containerTitle , out.print(containerTitle) will do but JSP with embedded Java printing code is rather ugly... 如果只想打印containerTitle的值,则可以使用out.print(containerTitle) ,但是带有嵌入式Java打印代码的JSP很难看...

First, you should avoid using Java Inline Code ( <% ... &> ). 首先,您应该避免使用Java内联代码( <% ... &> )。 Sometimes it is necessary, but code like this tends to be less readable, violates separation of concerns and insecure. 有时这是必要的,但是这样的代码往往可读性差,违反了关注点分离和不安全感。

To solve your problem, your servlet should place put the needed values into the request: 为了解决您的问题,您的servlet应该将所需的值放入请求中:

    request.setAttribute("containerTitle", "Your search for Foo Bar has returned 9 matches”);

In your JSP, I'd suggest using JSTL to output the value: 在您的JSP中,建议使用JSTL输出值:

    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
    <div>
            <c:out value="${containerTitle}"/>
    </div>

You are not limited to pass Strings to setAttribute . 您不限于将Strings传递给setAttribute You may create a simple object containing the information and use "dot language" to access the attributes of the object: 您可以创建一个包含信息的简单对象,并使用“点语”访问该对象的属性:

    <div>
            <c:out value="${searchResult.title}"/>
    </div>

I'd suggest reading a good tutorial about JSP programming to dive deeper into the topic. 我建议阅读一本有关JSP编程的好教程,以更深入地研究该主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM