簡體   English   中英

RESTful Web服務-從表單獲取數據並從MySQL數據庫獲取信息

[英]RESTful Web Service - Taking data from a form and grabbing info from MySQL database

我有一個學生數據庫,必須使用他們的電子郵件和密碼登錄到課程顧問網站。 我已經在數據庫中對一些學生進行了硬編碼以對其進行測試,我讓Facade做了它需要做的事情,但是我對其中的“服務”部分以及網頁如何將數據發送到服務並調用該服務感到困惑我創建的外觀方法。 這是一些代碼。

@Path("/Students/{email}")
@GET
@Produces("text/plain")
@Consumes("application/x-www-form-urlencoded")
public static Student getStudent(@FormParam("studentpass") String password, @FormParam("studentemail") String email)
{
    PlannerFacade pf = new PlannerFacade();
    Student x = pf.getStudent(email, password); //returns null if the password does not match the one in the Database.  Else returns the Student's toString();
    return x;
}

我對路徑如何與{email}一起使用以及它們通常如何工作感到困惑。

這是我的JavaScript代碼:

function getStud(responseType) {
    var status=0;
    var theEmail = document.getElementById("studform").studentmail.value;
    var url = "http://localhost:8080/CP/Students/"+theEmail;
    alert(url);
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("x").innerHTML=xmlhttp.responseText;
        }
      };
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
};

現在,我只是將一個空白的div設置為“ x”,而我只是想看看是否可以使腳本正確調用服務,並更改ID為“ x”的div以顯示學生的信息。 我的同班同學正在談論結合使用JQuery和Ajax,您是否知道有什么使它更容易理解的?

好,所以這里有很多事情。

首先,您的服務端點應該看起來像這樣:

@Path("/students/{username}")
@GET
@Produces("application/json")
public Student getStudent(@HeaderParam("password") String password, @PathParam("username") String username)

讓我解釋:

  • 我做到了,所以路徑將類似於“ / students / bob”。 帶有特殊字符的實際電子郵件可能會增加您在學習的這個階段不想處理的怪異感。
  • 我將密碼放在HTTP標頭中。 這也是不安全的,但是我忍不住把它放在路上。
  • 這些參數的相應位置指示我擁有@PathParam@HeaderParam的原因。
  • 無需static
  • 之所以產生JSON,是因為顯然您想將Student對象發回。 這意味着您需要使用從數據庫中獲取的數據填充Student對象,並將其序列化為REST客戶端可以讀取的JSON。

從MySQL獲取數據后,您將執行以下操作:

Student s = new Student("Bob Smith");
s.setStatus("Passing");
//just all the stuff you need to create a Student in Java.

然后,您將需要配置REST框架以使用JSON序列化器(如JacksonGSON等)將此Java對象轉換為如下所示的JSON:

{'name':'Bob Smith', 'status': 'Passing'}

如果配置正確,轉換將“正常工作”。 然后,您的JavaScript REST客戶端將知道如何處理生成的JSON。

至於JavaScript,您的學生是對的。 使用抽象而不是四處瀏覽DOM和XHR的底層細節。 JQuery和其他任何一個一樣好。 您可以在此處找到有關如何使用JQuery的$.post 信息 想一想,也許我們應該做一個關於這個主題的視頻教程。

希望這可以幫助。

暫無
暫無

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

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