JAVA REST jersy + Eclipse + MYSQL 将数据插入数据库

Posted

技术标签:

【中文标题】JAVA REST jersy + Eclipse + MYSQL 将数据插入数据库【英文标题】:JAVA REST jersy + Eclipse + MYSQL insert data into db 【发布时间】:2018-05-09 00:50:35 【问题描述】:

我是网络服务的新手, chrome调试器内部出现错误: http://localhost:8080/CRUDrestApp/REST/WebService/addUser500(内部服务器错误)

并且在邮递员应用程序中出现错误: http://localhost:8080/CRUDrestApp/REST/WebService/addUser?regUserName=a 状态:415 不支持的媒体类型

要修复此错误,我需要做哪些必要的更改?

FeedService.java>>

package webService;

import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import model.AddUserManager;
import model.GetUserManager;
import com.google.gson.Gson;
import dto.FeedObjects;
import dto.AddUserObject;

@Path("/WebService")
public class FeedService 
    //for insert query
    @POST
    @Path("/addUser")
    @Consumes("application/json")
    @Produces("application/json")
    public void reguserdata(AddUserObject reguserData)
    
        String feeds  = null;
        try 
               
            //StringBuffer sb = new StringBuffer();
            System.out.println("Inside reguserdata");
            Gson gson = new Gson();
            System.out.println("Inside add User web service::"+gson.toJson(reguserData));
            feeds = gson.toJson(reguserData);
            AddUserManager projectManager= new AddUserManager();
            projectManager.SetFeeds(feeds);

         catch (Exception e)
        
            System.out.println("error");
        
    

AddUser.Java>>>

package dao;

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

import dto.AddUserObject;


public class AddUser 



    public  ArrayList<AddUserObject> GetFeeds(Connection connection, String receivedData) throws Exception
    
        ArrayList<AddUserObject> regData = new ArrayList<AddUserObject>();
        String receivedData1 = receivedData;
        try
        
            //String uname = request.getParameter("uname");

            //PreparedStatement ps = connection.prepareStatement("SELECT * from users");
            //ps.setString(1,uname);
                //PreparedStatement ps = connection.prepareStatement("insert into users(username,password,hint1,hint2,emailid,uid) values(?,?,?,?,?,?)");
            PreparedStatement ps = connection.prepareStatement("insert into users (username) values (?)");

                AddUserObject feedObject = new AddUserObject();

                 System.out.println("Add>>receivedData1.valueOf(0):"+receivedData1.valueOf(0)); 
                 feedObject.setRegUserName(receivedData1.valueOf(0));



                 System.out.println("Add>>getRegUserName:"+feedObject.getRegUserName());                
                 ps.setString(1, feedObject.getRegUserName());              
//               ps.setString(2, feedObject.getRegPassword());
//               ps.setString(3, feedObject.getRegHint1());
//               ps.setString(4, feedObject.getRegHint2());
//               ps.setString(5, feedObject.getRegEmail());
//               ps.setString(6, feedObject.getRegUid());

                 regData.add(feedObject);


             ps.executeUpdate();
             ps.close();
            return regData;
        
        catch(Exception e)
        
            throw e;
        
    


AddUserObject.java>>>

package dto;

public class AddUserObject 

    private String regId;
    private String regusername;
    private String regpassword;
    private String reghint1;
    private String reghint2;
    private String regemail;
    private String reguid;


    /**
     * @return the url
     */
    public String getRegId() 
        return regId;
    
    /**
     * @param reguid  to set
     */
    public void setRegId(String regId) 
        this.regId = regId;
    
    /**
     * @return the title
     */
    public String getRegUserName() 
        return regusername;
    
    /**
     * @param title the title to set
     */
    public void setRegUserName(String regusername) 
        this.regusername = regusername;
    
    /**
     * @return the description
     */
    public String getRegPassword() 
        return regpassword;
    
    /**
     * @param description the description to set
     */
    public void setRegPassword(String regpassword) 
        this.regpassword = regpassword;
    
    /**
     * @return the url
     */
    public String getRegHint1() 
        return reghint1;
    
    /**
     * @param url the url to set
     */
    public void setRegHint1(String reghint1) 
        this.reghint1 = reghint1;
    

    /**
     * @return the url
     */
    public String getRegHint2() 
        return reghint2;
    
    /**
     * @param url the url to set
     */
    public void setRegHint2(String reghint2) 
        this.reghint2 = reghint2;
    

    /**
     * @return the url
     */
    public String getRegEmail() 
        return regemail;
    
    /**
     * @param reguid  to set
     */
    public void setRegEmail(String regemail) 
        this.regemail = regemail;
    

    /**
     * @return the url
     */
    public String getRegUid() 
        return reguid;
    
    /**
     * @param reguid  to set
     */
    public void setRegUid(String reguid) 
        this.reguid = reguid;
    

AddUserManeger.java>>>

package model;

import java.sql.Connection;
import java.util.ArrayList;

import dao.Database;
import dao.AddUser;
import dto.AddUserObject;

public class AddUserManager 


    public static ArrayList<AddUserObject> SetFeeds(String feeds2)throws Exception 
        ArrayList<AddUserObject> feeds = null;
        String receivedData = feeds2;
        try 
                Database database= new Database();
                Connection connection = database.Get_Connection();
                AddUser project= new AddUser();
                feeds=project.GetFeeds(connection , receivedData);

         catch (Exception e) 
            throw e;
        
        return feeds;
    


app.js>>

 var app = angular.module("mainApp", ['ngRoute','ngAnimate']);
var baseUrl ="http://localhost:8080/CRUDrestApp/REST/WebService";  
console.log("Inside App js");
app.config(['$routeProvider', function($routeProvider) 
            $routeProvider.
            when('/', 
                templateUrl: 'home.html',
                controller: 'homeCtrl'
             ). 
            when('/register', 
               templateUrl: 'register.html',
               controller: 'registerCtrl'
            ).  
            when('/login', 
                templateUrl: 'login.html',
                controller: 'loginCtrl'
            ).
            otherwise(
                templateUrl: 'home.html',
                controller: 'HomeCtrl'
            );
         ]);


app.controller('NavController', function ($scope, $location) 
    $scope.isCollapsed = true;
    $scope.$on('$routeChangeSuccess', function () 
        $scope.isCollapsed = true;
    ); 

    $scope.getClass = function (path) 
    if(path === '/') 
        if($location.path() === '/') 
            return "active";
         else 
            return "";
        
    

    if ($location.path().substr(0, path.length) === path) 
        return "active";
     else 
        return "";
    


);

app.controller('homeCtrl', function($http, $scope, $timeout) 

);

app.controller('loginCtrl', function($http, $scope, $timeout) 

);

console.log("after route provider");
app.controller('registerCtrl', function($http, $scope, $timeout) 
  console.log('inside registerAppCtrl controller');

    $scope.addUser = function() 
        var userdetails = JSON.stringify($scope.userAdd);
        console.log("$scope.userAdd::"+userdetails);
        if($scope.userAdd.regUserName == "" || $scope.userAdd.regUserPass == "" || $scope.userAdd.regUserCPass == "" || $scope.userAdd.regHint1 == "" || $scope.userAdd.regHint2 == "")
            console.log('Insert mandatory field values');
        
        else   
                    $.ajax(
                        url: baseUrl + '/addUser',
                        dataType: 'json',
                        type: 'post',
                        contentType: 'application/json ',
                        data: userdetails,
                        success: function( data, textStatus, jQxhr )
                        //$('#response pre').html( data );
                        console.log("successfully retrived response from server:::"+data);
                        /* console.log(data); */
                        $scope.userAdd = '';
                    ,
                    error: function( jqXhr, textStatus, errorThrown )
                            console.log( errorThrown );
                        
                    );     
        
     ;
);

注册.html

<section id="" ng-controller="registerCtrl">    
<form>
<div>
    User Name
</div>
<div>
    <input type="text" ng-model="userAdd.regUserName" required>
</div>
<div>
    Password
</div>
<div>
    <input type="password" ng-model="userAdd.regUserPass" >
</div>
<div>
    Confirm Password
</div>
<div>
    <input type="password" ng-model="userAdd.regUserCPass" >
</div>
<div>
    Enter Hint1
</div>
<div>
    <input type="text" ng-model="userAdd.regHint1" >
</div>
<div>
    Enter Hint2
</div>
<div>
    <input type="text" ng-model="userAdd.regHint2" >
</div>
<div>
    Enter UID
</div>
<div>
    <input type="text" ng-model="userAdd.regUid" >
</div>
<div>
    <input type="submit" name="Register" value="Register" ng-click="addUser()">
</div>
<div>
    <a href="login.html" target="_self">Login</a>
</div>
</form>

</section>

【问题讨论】:

尝试调试你的程序。另请参阅this SO Postman 问题。 【参考方案1】:

在 AddUserObject.java 中创建一个空的构造函数

public AddUserObject()

【讨论】:

System.out.println("内部添加用户web服务::"+gson.toJson(reguserData));这行打印什么东西吗?如果不是,可能是您的邮递员客户端中没有特定的内容类型。 不,它不打印任何东西。有人帮我修复它请 通过使用数据类型作为 Web 服务参数中的字符串而不是 addUserObject 解决的问题

以上是关于JAVA REST jersy + Eclipse + MYSQL 将数据插入数据库的主要内容,如果未能解决你的问题,请参考以下文章

怎么应用Protobuf 和Jersy 打造Rest Service

Eclipse JAX-RS (REST Web Services) 2.0 requires Java 1.6 or newer

Jmeter +Eclipse测试火币网REST API 实战案例(上)

自动在 JIRA Adaptavist 工具中发布测试结果,来自 Eclipse 上运行的 rest api 测试用例

如何在eclipse上配置rest服务啊

具有过期 JWT 和 Eclipse 微配置文件的 REST 客户端