将java文件添加到jsp文件

时间:2015-06-30 09:15:10

标签: java json jsp

我已经习惯了PHP,刚刚开始使用Java服务器端脚本。我被告知使用scriptlet是不好的做法,但我还是将它们用于测试目的。

<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%@page import="java.net.*"%>
<%
    String url = "https://www.google.com/recaptcha/api/siteverify";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "USER_AGENT");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    String urlParameters = "secret=6LeI6AgTAAAAAGJDs5rvWB67-d7n5YjN61JW1RKn&response="
+request.getParameter("g-recaptcha-response");

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    out.println("\nSending 'POST' request to URL : " + url);
    out.println("Post parameters : " + urlParameters);
    out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer responses = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        responses.append(inputLine);
    }
    in.close();
    out.println(responses.toString());  
%>

这里的内容与问题无关。我需要一种解析json响应的方法,这在PHP中使用json_decode()非常简单。
我已经下载了JSONObject.java,JSONString.java ...以及http://www.json.org/java/index.html给出的所有java文件。

有没有办法可以包含这些java文件,所以我可以使用这些java文件中可用的类?
我认为这将是:

<%@page import="JSONArray.*"%>

1 个答案:

答案 0 :(得分:0)

You cannot import .java files, you have to import (compiled) classes. Download compiled .class files, or better, a .jar file with the whole library (because the separate classes most probably won't work) and place it into WEB-INF/lib folder of your web application. Then you can import the class(es) from the library using the above mentioned page import directive, e.g.

<%@page import="org.json.JSONArray" %>

You have to specify the fully qualified name of the class, i.e. org.json.JSONArray, just JSONArray is not enough. And you will probably need to restart (reload) your web application, or even the (Java) server.

If you are going to tackle with Java/JSP more, I would recommend you to study some basics. Start with learning what the classpath is, then you can continue here.