简体   繁体   中英

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

I have problem of inserting data in my database Table from HTML page. When ever I run the application and send the data, all my fields in the Table will be NULL.

This is my database connection class

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();
        }
    }

}

This is my userVo class

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;
     }
}

This is my Service class

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);
}

This is my JS file

// 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()
        });
}

This is my SignUpHandler Class

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;
     }



}

This is my HTML Form

<!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>

You use $('#UserName').val() to get the value of the user name text input, but this text input doesn't have the id UserName . It has the name UserName . So you actually want

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

or, more simply

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

(same for all the other fields, of course)

Side note: what's the point of catching an exception only to rethrow it? This adds unnecessary lines to your code, and make it more difficult to identify the source of an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM