JSP java动态Web项目中的图像没有刷新

时间:2016-05-12 17:38:56

标签: java html image jsp web

构建网络应用,用户可以在其中搜索单词并返回相关图片。但是,只要查询更改,图片就不会。这是怎么回事?

用户搜索" cat"和图像回来了。但在第一次查询后仍然保持这样。 enter image description here

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>
<style>
    .fit_image img {
        max-width: 100%;
        max-height: 100%;
    }
    .fit_image {
        width: 400px;
        height: 200px;
    }
</style>

</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:
        <div class="fit_image">
        <img src="<%=request.getAttribute("onelink")%>"/>
</div>





    </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.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 {
        request.removeAttribute("onelink");

        // Get query from user through http parameter

        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
        String[] urlAry = results.split("\n");
        ArrayList<String> ar = new ArrayList<String>();
        ar.clear();
        ar.removeAll(ar);
        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 = "*********private key************";
        URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
                + "&cx=*********private key************&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;
    }

}

关于为什么会发生这种情况的任何想法?谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

我认为问题与使用静态方法有关。我删除了静态声明,更改了一些代码,现在似乎可以正常工作。

<强> google2.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 google2 {
    StringBuilder results = new StringBuilder();
    String finalResults;


    public  String psuedomain(String qry) throws IOException {

        String key = "*********private key************";
        URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
                + "&cx=*********private key************&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  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;
    }

    public String finalResults(String query){

        try {
            psuedomain(query);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return finalResults;


    }

}

<强> Link2Servlet.java

package googleAPI;

import java.io.IOException;
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;

@SuppressWarnings("serial")
@WebServlet("/Link2Servlet")
public class Link2Servlet extends HttpServlet {


    public Link2Servlet() {
        super();
    }

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


        String query = request.getParameter("query");

        google2 google = new google2();

        String test = google.finalResults(query);



        String[] urlAry = test.split("\n");
        ArrayList<String> ar = new ArrayList<String>();

        for (int i = 0; i < urlAry.length; i++) {
            ar.add(urlAry[i]);
        }


        request.setAttribute("onelink", ar.get(0));


        request.setAttribute("links", ar);

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/DefineWord.jsp");

        dispatcher.forward(request, response);

    }

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

    }

}