Jersey RESTful POST操作获取@PathParam的空值,并且不在MySQL中插入期望值

时间:2016-12-07 18:45:39

标签: rest post jersey-2.0 mysql-error-1064

//你好, //我的RESTful POST操作如下

import java.sql.SQLException;
import java.util.ArrayList;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.transaction.annotation.Transactional;

@Path("/dbuser")
public class DBUserRestServices extends DbConnectionDAO{


@POST
    @Path("/postuser1")  //Problem here???
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED})
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED})
    @Transactional
    public Response userPOSTOperation( @PathParam("userid") int userid,@PathParam("username") String username,
            @PathParam("password") String password) throws SQLException{

        UserObject userobj = new UserObject(userid, username, password);
        username= userobj.getUsername();
        password= userobj.getPassword();
        System.out.println("UserName " + username + "\t\t"+ "Password :" + password);   

        dbConnection = new DbConnectionDAO();
        String sqlQuery = "INSERT INTO user (username, password) values ('" +"username" +"',"+ "'password" +"')";

        System.out.println("Query executed : " + sqlQuery );

        try{
            connection = DbConnectionDAO.setDBConnection();
            statement = connection.createStatement();
            numRowsChanged = statement.executeUpdate(sqlQuery);

            System.out.println("numRowsChanged : " + numRowsChanged );
            if (numRowsChanged<=0)
            {
                System.out.println("Oops!! The insertion operation failed");
            }
            else{
                System.out.println("The POST operation with username = " + username + ", password "+ password+" has been completed");
            }

        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        return Response.ok().build();

    }


}

//
// The DbConnectionDAO.java file is 

public class DbConnectionDAO {

    public static Connection connection;
    public static Statement statement;
    public static PreparedStatement pst;
    public static ResultSet rs = null;
    private static String sqlQuery = null;

    static int numRowsChanged = 0;

    public static Connection setDBConnection() throws Exception
    {
        try
        {
            String connectionURL = "jdbc:mysql://localhost:3306/test";

            //  Connection connection = null;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, "root", "password");
            if (connection != null) {
                // System.out.println("Connected to the Database...");
            }

            return connection;
        }
        catch (SQLException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw e;
        }

    }


// The UserObject.java file is 

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "userObject")
public class UserObject {
    private int userid;
    private String username;
    private String password;

      public UserObject(){}

       public UserObject(int userid, String username, String password){
          this.userid = userid;
          this.username = username;
          this.password = password;
       }

    public String getPassword() {
        return password;
    }
    public int getUserid() {
        return userid;
    }
    public String getUsername() {
        return username;
    }

    @XmlElement
    public void setPassword(String password) {
        this.password = password;
    }

    @XmlElement
    public void setUserid(int userid) {
        this.userid = userid;
    }

    @XmlElement
    public void setUsername(String username) {
        this.username = username;
    }

}

当我在Postman中提供以下命令时:http://localhost:8080/iAdjuster/restapi/dbuser/postuser1/?username=John&password=Michael

它显示以下控制台输出:

UserName null密码:null 执行查询:INSERT INTO用户(用户名,密码)值('用户名','密码') numRowsChanged:1 使用username = null,密码为null的POST操作已完成

然而,MySQL数据库在用户名和密码字段中显示了一个成功的INSERtion值,其中包含'username'和'password'以及自动增量用户ID。

任何人都可以帮我解决我的问题。

先谢谢!!

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题 -

  1. 您使用的是POST方法,但您的逻辑与POST数据处理无关。因此,确定并决定是否要发送GET请求或POST请求。如果您要在请求URI中发送所有数据,则无需使用POST方法,而应使用GET方法。

  2. 在您的调用命令中,您将'username'和'password'作为查询参数传递,而在REST API中,您将它们作为Path参数接收。路径参数和查询参数之间存在差异。此外,您尚未在@Path注释中定义“用户名”和“密码”。这就是原因,它们是空的。

  3. 您的方法声明应如下所示 -

    @POST
    @Path("/{userid}/{username}/{password}") 
    @Transactional
    public Response userPOSTOperation( @PathParam("userid") int userid,@PathParam("username") String username,
            @PathParam("password") String password) throws SQLException{
    

    您应该能够使用URI发送POST请求 -

    http://localhost:8080/iAdjuster/restapi/dbuser/userId/John/Michael
    
    1. 此外,您的SQL查询错误。 SQL查询应该是 -

      String sqlQuery =“INSERT INTO user(用户名,密码)值('”+ username +“','”+ password +“')”;