-1

I'm learning about servlets in java and I'm trying to capture a URL content and store it into a string array. Bellow is my code that I put together following some tutorials that does not seem to work servlet environment (This is the first part of an exercise that I'm trying to do).

I'm getting the error at this line:

cookies.add(line);

Here is the complete code:

//package fortune;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static java.util.Arrays.*;

@WebServlet(name = "FortuneServlet", urlPatterns = {"/"})
public class FortuneServlet extends HttpServlet {
    private String [] cookies = null;
    //ArrayList<String[]> cookies = new ArrayList<String[]>();

    public void geturl(String[] args) {

        try 
        {
         URL url = new URL(" http://fortunes.cat-v.org/openbsd/");
         // read text returned by server
             BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
         String line = in.readLine();

         while((line = in.readLine()) != null)
         {
              cookies.add(line);
              line = in.readLine();
         }
            in.close();

    }
        catch (java.net.MalformedURLException e) {
            System.out.println("Malformed URL: " + e.getMessage());
        }
        catch (IOException e) {
            System.out.println("I/O Error: " + e.getMessage());
        }
    }
    public void init() throws ServletException {
        // Add your own code here!
        // 1) Open the URL
        // 2) Get the contents
        // 3) Extract the cookie texts to an array


    }

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

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");
        if (cookies != null) {
            response.getWriter().println(
                cookies[new Random().nextInt(cookies.length)]

            );
        } else {
            response.getWriter().println("No luck!");
        }
    }
}
4

2 回答 2

3
private String [] cookies = null;

在这里,您初始化一个字符串数组并将其设置为 null。

cookies.add(line);

在这里,您假设add()数组有一个方法,但它没有。

List您应该使用具有该方法的注释掉的解决方案add()。您不应该使用数组列表,而是使用字符串列表:

List<String> cookies = new ArrayList<>();

然后你可以按照你已经做的方式添加cookies:

cookies.add(line);
于 2015-10-02T09:01:22.810 回答
0

您不能add()在数组上使用方法。你必须使用列表。所以而不是

private String [] cookies = null;

利用

private List<String> cookies = new ArrayList<String>();
于 2015-10-02T09:01:29.893 回答