java - 使用 Jersey(JAX-RS)、MySQL 和 Eclipse 开发 Java Web 服务

标签 java

我在从 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 用户名。它具有名称 用户名。所以你实际上想要

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

或者,更简单

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

(当然,所有其他字段都相同)

旁注:捕获异常只是为了重新抛出它有什么意义?这会向您的代码添加不必要的行,并使识别异常源变得更加困难。

关于java - 使用 Jersey(JAX-RS)、MySQL 和 Eclipse 开发 Java Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873729/

相关文章:

java - 在 Java 中调整 base64 字符串图像的大小

java - 如何在 JTextField 中设置不同的限制以显示输入提示和输入

java - com.fasterxml.jackson.databind.exc.InvalidDefinitionException

字符串的Java正则表达式以数字和固定长度开头

java - 如何将文本发送到在 selenium webdriver 中使用自动完成功能的搜索框

java - 使用数组中的参数进行 Vararg 初始化 (Java)

java - 如何在 play (2.3) 框架内从 Java Controller 代码中的 String 变量构造 Html 对象

java - SQL 查询查找与 Toplink 中的日期相等的行

java - 当我运行 .jar 时,出现 "No lwjgl in java.library.path"错误

java - 方法体的参数列表怎么可能有一个类?