简体   繁体   中英

Why is this ArrayList storing everything in first index? And how can one load image urls dynamically in JSP from that arraylist?

Building a web application that uses google custom search API to fetch images related to the users search query. So if you search " cheese ", you will get back images that are cheese related.

Here is an example of what it currently looks like: 在此处输入图片说明

There are two main problems.

  1. Why are all the query results being stored in the first index of my ArrayList? I only want one link for the moment.
  2. How could i get these links to display images?

Currently there are three pieces of code for this. a JSP , a Servlet and a Java class.

DefineWord.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="googleAPI.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Define</title>

<link rel="stylesheet" type="text/css" href="css/bootstrap.css">

<link rel="stylesheet" href="css/bootstrap-lightbox.min.css">
<link rel="stylesheet" href="css/bootstrap-lightbox.css">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/includeNAV.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

</head>
<body>



    <div id="includedNav"></div>


    <div class="container">
        <form id="searchForm" method="get" action="LinkServlet">
            <fieldset>

                <input id="s" type="text" name="query" /> <input type="submit"
                    value="Submit" id="submitButton" />


            </fieldset>
        </form>
    </div>
    <br />
<!--    Requests attributes from servlet -->

    <div class="container">
<%--        <%=request.getAttribute("links") %> --%>
        <br /> ONE LINK:
        <%=request.getAttribute("onelink") %>






    </div>
    <script
        src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script
        src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
    <script src="js/bootstrap-image-gallery.min.js"></script>

</body>
</html>

LinkServlet.java

package googleAPI;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    @WebServlet("/LinkServlet")
    public class LinkServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public LinkServlet() {
            super();
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            // Get query from user through http parameter
            PrintWriter printWriter = response.getWriter();
            String query = request.getParameter("query");
            String results = google.psuedomain(query);

            // Put results string into a ArrayList so that the jsp can dynamically
            // call each image
            printWriter.println(results);
            String[] urlAry = results.split(" ");
            ArrayList<String> ar = new ArrayList<String>();
            for (int i = 0; i < urlAry.length; i++) {
                ar.add(urlAry[i]);
            }

            // Get first element from ArrayList and set attribute
            String onelink = ar.get(0);
            request.setAttribute("onelink", onelink);

            // Set query results to attribute so JSP can call it
            request.setAttribute("links", ar);

            // Forward request back to the same JSP.
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/DefineWord.jsp");
            dispatcher.forward(request, response);

        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

        }

    }

google.java

package googleAPI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;

public class google {
    static StringBuilder results = new StringBuilder();
    static String finalResults;

    public static String getFinalResults() {
        return finalResults;
    }

    public static void setFinalResults(String finalResults) {
        google.finalResults = finalResults;
    }

    public static String psuedomain(String qry) throws IOException {

        String key = "*********privatekey*********";
        URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
                + "&cx=*********privatekey*********&q=" + qry + "&alt=json");

        // CONNECTION LOGIC
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String output;
        while ((output = br.readLine()) != null) {
            Pattern pattern = Pattern.compile("(?:(?:https?)+\\:\\/\\/+[a-zA-Z0-9\\/\\._-]{1,})+(?:(?:jpe?g|png|gif))");
            Matcher matcher = pattern.matcher(output);
            if (matcher.find()) {
                results.append(matcher.group() + "\n");
            }

        }
        conn.disconnect();
        finalResults = removeDup();
        return finalResults;
    }

    public static String removeDup() {
        String[] tokens = results.toString().split("\n");
        StringBuilder resultBuilder = new StringBuilder();
        Set<String> alreadyPresent = new HashSet<String>();

        boolean first = true;
        for (String token : tokens) {

            if (!alreadyPresent.contains(token)) {
                if (first)
                    first = false;
                else
                    resultBuilder.append("\n");

                if (!alreadyPresent.contains(token))
                    resultBuilder.append(token + "\n");
            }

            alreadyPresent.add(token);
        }
        String result = resultBuilder.toString();
        return result;
    }

}

Any ideas? Thanks for your time.

In the LinkServlet.java file, the doGet method, you split the google.psuedomain answer with a space " ", but they where concatenated using a new line "\\n". So, either split on new line or change the concatenation to use a space. Even better, why don't you return an ArrayList of String with the google.psuedomain method ?

To display all the links as images, use a foreach block in which you add an img tag with the src attribute set to the current link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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