2012-12-29 32 views
0

我有一個關於JAVA的問題(直接從URL讀取)。我想從URL中讀取內容。我剛剛在JAVA中實現了一個代碼,它運行良好。但我想要在JSP中實現該代碼。我試圖在JSP頁面上使用它,但它不讀取URL的內容。請幫助我。如何使用JSP與JAVA讀取URL

Java代碼

import java.net.*; 
import java.io.*; 

public class URLReader { 
    public static void main(String[] args) throws Exception { 

     URL oracle = new URL("http://www.oracle.com/"); 
     BufferedReader in = new BufferedReader(
     new InputStreamReader(oracle.openStream())); 

     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 
    } 
} 

JSP代碼

<%@ page import="java.sql.*,java.net.*,java.io.*,java.lang.*,java.util.*"%> 
<html> 
<title></title> 
<head></head> 
<body> 

<% 
try{ 
    URL oracle = new URL("http://www.oracle.com/"); 
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream())); 

    String inputLine; 
    while ((inputLine = in.readLine()) != null) 
     System.out.println(inputLine); 
    in.close(); 
    }catch(Exception ex){} 
%> 
</body> 
</html> 

我使用JDK1.5.0_16和Tomcat 3.0版

+6

Scriptlet代碼和空的catch塊是最糟糕的兩個想法。我建議學習JSTL並重新開始。 – duffymo

+2

Tomcat 3?真?生產版本是7.升級時間。 http://tomcat.apache.org/ – duffymo

+0

@duffymo ...哈哈哈..絕對,我會去版本7. – user1925483

回答

4

你在JSP中的錯誤是以下行加載屬性:

System.out.println(inputLine); 

這將輸出線到標準輸出(控制檯,日誌文件,等等),而不是HTTP響應。

使用隱out對象指的響應輸出流:

out.println(inputLine); 

或者,更好的,只是使用JSTL<c:import>Scriptlets are namely discouraged since a decade

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
... 
<c:import url="http://www.oracle.com" /> 

不要忘了升級你的古代(這是一個輕描淡寫......)服務器第一。考慮到你用JSP學習JSP的方式,我還想知道在學習JSP的時候你是否正在閱讀正確的和最新的資源。

+0

非常感謝你@BalusC – user1925483

+0

當然,我會分開保存我的java文件並根據需要調用所需的方法。我只是試圖直接從JSP頁面運行我的代碼。我只是想知道它如何與JSP一起使用。 – user1925483

0

您可以使用HttpClient庫作爲它非常易於使用您的任務 例如

HttpClient client = new DefaultHttpClient(); 
HttpGet request = new HttpGet("http://www.yahoo.com"); 
HttpResponse response = client.execute(request); 

// Get the response 
BufferedReader rd = new BufferedReader 
    (new InputStreamReader(response.getEntity().getContent())); 

String line = ""; 
while ((line = rd.readLine()) != null) { 
    textView.append(line); 
} 

這裏是一個tutorial

這對你來說不實現HttpClient的約束?另一點我想說的是在JSP腳本中放置這種邏輯是不好的,你應該使用一些服務類,它從URL中獲取值並從JSP中調用相同的值。您可以使用的setProperty和getProperty標籤從外部服務

<jsp:useBean id="some_identifier" class="Foo.class" /> 

<jsp:getProperty name="some_identifier" property="SomeProperty" /> 
+0

Akhilesh ..謝謝你的回覆。但是我被要求通過URL類來實現它。不是HttpClient類。 – user1925483

+0

一個通過使用在JSP中實現的URL類的例子會很棒。 – user1925483

+0

我編輯了答案 – Akhilesh