簡體   English   中英

如何從Java類中打JSP

[英]How to hit jsp from java class

如何在不使用servlet的情況下從Java類中打JSP? 我需要從客戶端計算機到服務器(tomcat)的參數,然后將其插入數據庫。

以下是我的Java類編碼:

public void callJSP(String fullContent) {

    // convert String into InputStream
    InputStream is = new ByteArrayInputStream(fullContent.getBytes());
    InputStreamReader isr;
    BufferedReader br;
    String line;
    URL url;
    URLConnection connection;
    ObjectOutputStream output;
    ObjectInputStream input;
    try {
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        line = br.readLine();
        url = new URL("http://localhost:8080/WebContent/FeedIssueToDB.jsp");
        connection = url.openConnection();
        connection.setDoOutput(true);
        output = new ObjectOutputStream(connection.getOutputStream());
        output.writeObject(line);
        output.close();
        /*input = new ObjectInputStream(connection.getInputStream());
        input.readObject();
        input.close();*/
        // TODO do your stuff here
    } catch (Exception ex) {
        // TODO
    }
}

這是JSP:

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage=""%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%
String fullContent= request.getParameter("line");
System.out.println("full content -"+fullContent);

  %>
  <%

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.55:1433/RTDATA_TT", "sa", "dominorich");
PreparedStatement ps=conn.prepareStatement("INSERT INTO SummaryFeedIssue(\"DateTimeIssue\", \"Source\", \"ServerIP\", \"Keywords\",\"Remarks\") VALUES (?,?,?,?,?)");

StringTokenizer st1 = new StringTokenizer(fullContent, "|");
String dateTime="";
String source="";
String serverIP="";
String keywords="";
String remarks="";
while (st1.hasMoreTokens()) {
    dateTime = st1.nextToken();
    source = st1.nextToken();
    serverIP = st1.nextToken();
    keywords = st1.nextToken();
    remarks = st1.nextToken();
 ps.setString(1,dateTime );
 ps.setString(2,source );
 ps.setString(3,serverIP );
 ps.setString(4,keywords );
 ps.setString(5,remarks );

ps.execute();
conn.close();

}

%>

運行該應用程序后,它沒有任何作用。我的編碼有錯嗎?

您不應該在JSP中編寫業務邏輯,而應該擁有一個具有業務邏輯的管理器或助手類,並在JSP中調用它們的方法。

但,

要運行代碼,您應該更改行

url = new URL("http://localhost:8080/WebContent/FeedIssueToDB.jsp");

url = new URL("http://localhost:8080/WebContent/FeedIssueToDB.jsp?line="+line);

無需將行寫入輸出流。

將行作為參數傳遞應該完成您打算要做的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM