簡體   English   中英

使用Jersey(JAX-RS),MySQL和Eclipse開發Java Web服務

[英]Developing Java web services using Jersey(JAX-RS), MySQL and Eclipse

我有從HTML頁面在數據庫表中插入數據的問題。 每當我運行應用程序並發送數據時,表中的所有字段都將為NULL。

這是我的數據庫連接類

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbConnection {

 public static Connection getConnection() throws Exception
 {
 try
 {
 String connectionURL = "jdbc:mysql://localhost:3306/dvd_collection";
 Connection connection = null;
 Class.forName("com.mysql.jdbc.Driver").newInstance();
 connection = DriverManager.getConnection(connectionURL, "root", "031081");
 return connection;
 }
 catch (SQLException e)
 {
 throw e;
 }
 catch (Exception e)
 {
 throw e;
 }
 }

 public static void close(Connection connection)
    {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

這是我的userVo類

package pojo;

public class UserVo {

 private String username;
 private String password;
 private String email;
 private String gender;
 private String occupation;
 private String marital;
 public String getUserName() {
 return username;
 }
 public void setUserName(String username) {
 this.username = username;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }

 public String getEmail() {
     return email;
     }
 public void setEmail(String email) {
     this.email = email;
     }
 public String getGender() {
     return gender;
     }
public void setGender(String gender) {
     this.gender = gender;
     }
public String getOccupation() {
     return occupation;
     }
public void setOccupation(String occupation) {
     this.occupation = occupation;
     }
public String getMarital() {
     return marital;
     }
public void setMarital(String marital) {
     this.marital = marital;
     }
}

這是我的服務班

package webService;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import pojo.UserVo;

@Path("/WebService")
public class SignUpService {

@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public UserVo create(UserVo user)throws Exception {
    System.out.println("creating user");
    return dao.create(user);
}

這是我的JS文件

// The root URL for the RESTful services
var rootURL = "http://localhost:8080/Test/REST/WebService";

$('#btnSubmit').click(function() {
    if ($('#UserName').val() == '')
        alert('User Name can not be empty');
    else
        addWine();
    return false;
});

function addWine() {
    console.log('addWine');
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: rootURL,
        dataType: "json",
        data: formToJSON(),
        success: function(data, textStatus, jqXHR){
            alert('Record created successfully: Login to your account');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('The User name already exist: ' + textStatus);
        }
    });
}

// Helper function to serialize all the form fields into a JSON string
function formToJSON() {
    return JSON.stringify({ 
        "username": $('#UserName').val(), 
        "password": $('#Password').val(),
        "email": $('#Email').val(),
        "gender": $('#Gender').val(),
        "occupation": $('#Occupation').val(),
        "marital": $('#MaritalStatus').val()
        });
}

這是我的SignUpHandler類別

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import dao.DbConnection;

import pojo.UserVo;

public class SignUpHandler {

public UserVo create(UserVo user) throws Exception {
     Connection c = null;
     PreparedStatement ps = null;
     try {
         c = DbConnection.getConnection();
         ps = c.prepareStatement("INSERT INTO signin (user_name, password, e_mail, gender, occupation, marital_status) VALUES (?, ?, ?, ?, ?, ?)",
             new String[] { "ID" });
         ps.setString(1, user.getUserName());
         ps.setString(2, user.getPassword());
         ps.setString(3, user.getEmail());
         ps.setString(4, user.getGender());
         ps.setString(5, user.getOccupation());
         ps.setString(6, user.getMarital());
         ps.executeUpdate();
         ResultSet rs = ps.getGeneratedKeys();
         rs.next();
         // Update the id in the returned object. This is important as this value must be returned to the client.

     } catch (Exception e) {
         e.printStackTrace();
         throw new RuntimeException(e);
        } finally {
            DbConnection.close(c);
        }
      return user;
     }



}

這是我的HTML表格

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
</head>
<body>

      <form class="form-signup">
        <h2 class="form-signin-heading">Please Register</h2>
        <input name="UserName" type="text" placeholder="Username">
        <input name="Password" type="password" placeholder="Password">
        <input name="Email" type="text" placeholder="Email">
        <input name="Gender" type="text" placeholder="Gender">
        <input name="Occupation" type="text" placeholder="Occupation">
        <input name="MaritalStatus" type="text" placeholder="Marital Status">
        <button type="submit" id="btnSubmit">Submit</button>

      </form>


      <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="js/jquery-1.8.2.js"></script>
    <script src="js/main.js"></script>

</body>
</html>

您使用$('#UserName').val()來獲取用戶名文本輸入的值,但是此文本輸入沒有id UserName 它的名稱為 UserName 所以你實際上想要

$('input[name="UserName"]').val()

或者,更簡單地說

<input name="UserName" id="UserName" type="text" placeholder="Username"/>

(當然,所有其他領域都一樣)

旁注:僅捕獲異常以重新拋出異常有什么意義? 這會在代碼中添加不必要的行,並使識別異常源變得更加困難。

暫無
暫無

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

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