2014-11-01 2 views
0

Я пытаюсь скомпилировать некоторый код и заставить его работать должным образом в этой программе индексирования веб-сервисов, которую я создал, через виртуальную машину.Код веб-сервера не работает должным образом

package com.cs330; 
import javax.ws.rs.*; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 

@Path("ws2") 
public class IngredientServices 
{ 
@Path("/ingredients") 
@GET 
@Produces("text/plain") 
public String getIngredients() throws SQLException, ClassNotFoundException { 

String connectStr="jdbc:mysql://localhost:3306/fooddb"; 
//database username 

String username="root"; 
//database password 

String password="csci330pass"; 
/* The driver is the Java class used for accessing 
    * a particular database. You must download this from 
    * the database vendor. 
    */ 

String driver="com.mysql.jdbc.Driver"; 
Class.forName(driver); 
//Creates a connection object for your database 

Connection con = DriverManager.getConnection(connectStr, username, password); 
/* Creates a statement object to be executed on 
    * the attached database. 
    */ 

Statement stmt = con.createStatement(); 
/* Executes a database query and returns the results 
    * as a ResultSet object. 
    */ 

ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient"); 
/* This snippet shows how to parse a ResultSet object. 
    * Basically, you loop through the object sort of like 
    * a linkedlist, and use the getX methods to get data 
    * from the current row. Each time you call rs.next() 
    * it advances to the next row returned. 
    * The result variable is just used to compile all the 
    * data into one string. 
    */ 

    String result = ""; 
    while (rs.next()) 
    { 
    int theId = rs.getInt("id"); 
    String theName = rs.getString("name"); 
    String theCategory = rs.getString("category"); 
    result += "id: "+theId+ " , name: "+theName + "("+theCategory+")" + "\n" + "\n"; 
    } 
    return result; 
    }//END METHOD 

@Path("/ingredients/{id}") 
@GET 
@Produces("text/plain") 
public String getIngredientById(@PathParam("id") String theId) 
throws SQLException, ClassNotFoundException { 
int intId = 0; 
try 
{ 
    intId = Integer.parseInt(theId); 
} 
catch (NumberFormatException FAIL) 
{ 
    intId = 1; 
}//Obtaining an ingredient from the database 

String connectStr="jdbc:mysql://localhost:3306/fooddb"; 
String username="root"; 
String password="csci330pass"; 
String driver="com.mysql.jdbc.Driver"; 
Class.forName(driver); 
Connection con = DriverManager.getConnection(connectStr, username, password); 
Statement stmt = con.createStatement(); 
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient 
WHERE id=" +intId); 

String result = ""; 
while (rs.next()) 
{ 
    int theId2 = rs.getInt("id"); 
    String theName2 = rs.getString("name"); 
    String theCategory = rs.getString("category"); 
    result += "id: "+theId2+ " , name: "+theName2 + "("+theCategory+")" + "\n" + "\n"; 
} 
    return result; 
}//END METHOD 

@Path("/ingredients/name") 
@GET 
@Produces("text/plain") 
public String getIngredientByName(@QueryParam("name") String theName) 
throws SQLException, ClassNotFoundException 
{ 
//Obtaining an ingredient from the database 
String connectStr="jdbc:mysql://localhost:3306/fooddb"; 
String username="root"; 
String password="csci330pass"; 
String driver="com.mysql.jdbc.Driver"; 
Class.forName(driver); 
Connection con = DriverManager.getConnection(connectStr, username, password); 
Statement stmt = con.createStatement(); 
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient WHERE 
name='" + theName + "'"); 

String result = ""; 
while (rs.next()) 
{ 
    int theId3 = rs.getInt("id"); 
    String theName3 = rs.getString("name"); 
    String theCategory = rs.getString("category"); 
    result += "id: "+theId3+ " , name: "+theName3 + "("+theCategory+")" + "\n" + "\n"; 
} 
    return result; 
}//END METHOD 
}//END CODE 

Теперь первые два метода, которые должны получить все и получить детали ID работают должным образом, это путем извлечения с помощью NAME кода, который не является. Хотя он компилируется правильно, когда я запускаю его на cmd на своей виртуальной машине и не показываю никаких ошибок на Tomcat 8, единственным кодом, который дает мне результаты, являются первые два метода. По какой-то причине третий метод продолжает выплевывать первый результат и только первый результат.

Я также прилагается код index.html файл, чтобы показать вам, что приведенный выше код работает с ...

<html> 
<head> 
<title>Shakur (S-3) Burton's Web Services</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> 
</script> 
<script> 
$(document).ready(function() { 
alert("running script"); 
$("#btnAll").click(function() { 
alert("clicked"); 
$.ajax({ 
url:"http://localhost:8080/webserv1/resources/ws2/ingredients/", 
type: "GET", 
dataType: "text", 
success: function(result) { 
alert("success"); 
$("#p_retrieveAll").html(result); }, 
error:function(xhr) { 
alert("error"); 
$("#p_retrieveAll").html("Error:"+xhr.status + " " + xhr.statusText);} 
}); 
}); 
$("#btnOneId").click(function() { 
alert("clicked"); 
var inputId=document.getElementById("t_ingredId").value; 
var theUrl = "http://localhost:8080/webserv1/resources/ws2/ingredients/"+inputId; 
$.ajax({ 
url: theUrl, 
type: "GET", 
dataType: "text", 
success: function(result) { 
alert("success"); 
$("#p_retrieveOneId").html(result); }, 
error:function(xhr) { 
alert("error"); 
$("#p_retrieveOneId").html("Error:"+xhr.status+" "+xhr.statusText);} 
}); 
}); 
$("#btnOneName").click(function() { 
alert("clicked"); 
var inputName=document.getElementByName("t_ingredName").value; 
var theUrl: "http://localhost:8080/webserv1/resources/ws2/ingredients/ingredient?name="+inputName; 
$.ajax({ 
url: theUrl, 
type: "GET", 
dataType: "text", 
success: function(result) { 
alert("success"); 
$("#p_retrieveOneName").html(result); }, 
error:function(xhr) { 
alert("error"); 
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);} 
}); 
}); 
}); 
</script> 
</head> 
<body> 
<h3>Testing Web Services</h3> 
<div id="retrieveAll"> 
<button id="btnAll">Click to Retrieve All</button> 
<p id="p_retrieveAll">Ingredients List Goes here</p> 
</div> 
<div id="retrieveOneId"> 
<input type="text" id="t_ingredId" value="type id here" /> 
<button id="btnOneId">Click to Retrieve by Id</button> 
<p id="p_retrieveOneId">Ingredient By Id Goes here</p> 
</div> 
<div id="retrieveOneName"> 
<input type="text" id="t_ingredName" value="type name here"/> 
<button id="btnOneName">Click to Retrieve by Name</button> 
<p id="p_retrieveOneName">Ingredient By Name Goes here</p> 
</div> 
</body> 
</html> 

Есть ли какие-либо предложения, которые могут быть предложены здесь, почему GET методом NAME в моем javascript IngredientServices работает неправильно? Я что-то упускаю?

EDIT - 11/4/2014 - 16:05 ...

я понял, что эта проблема может быть в этой части программы базы данных ... Вместо того, чтобы искать компонент по имени Найдя сказал элемент по ID, я должен искать в пределах заданных параметров для него с помощью NAME. Надеюсь, это устраняет проблему, с которой я столкнулся ...

BTW, это предыдущий код, который я изменил: var inputName = document.getElementByName ("t_ingredName"). Значение;

+0

Когда вы выполняете команду sql непосредственно с базой данных для имени, вы получаете несколько результатов назад? –

+0

Если вы получаете только один результат при выполнении sql для базы данных, это означает, что в базе данных есть только одна соответствующая запись, и ваш код работает должным образом. –

+0

Потратив некоторое время, чтобы лучше изучить вещи. Я принял ваш совет как указано. Казалось бы, это может быть что-то в index.html, вызывающее у меня эту головную боль проблемы. – user2891351

ответ

0

Когда я добавил код в Firefox и Нажал на Надстройка под названием Firebug, он показал мне следующую ошибку:

SyntaxError: missing ; before statement 
var theUrl: "http://localhost:8080/webserv1/resources/ws2/ingredients/ 

Поэтому она должна быть var theUrl= "http://localhost:8080/webserv1/resources/ws2/ingredients/ingredient?name="+inputName;

Вы пробовали отладки ?

Кроме того, вместо использования предупреждений используйте console.log("your message here"); - он появится на консоли в Firebug.

+0

причина была ..... вместо localhost: 8080 связано с тем, что, когда я пытался ввести это, это не позволило мне. Сожалею. Однако я знаю, что это правильная ссылка. – user2891351

0

Оказывается, что код, который я создал в приведенном выше вопрос, к счастью, работает должным образом, несмотря на некоторые несчастные ошибки в Получить Ингредиент По имени метод моего Java кода ... Это было в конечном счете то, что нужно некоторое фиксирование ,

Смежные вопросы