简体   繁体   中英

REST server connect to databse and fetch data

I'm new to JAVA and web services.

I want to call a method in REST client JAVA Desktop application. Client is in NetBeans IDE and it should be something like a framework, where it calls the REST server (A dynamic web project), Server is in Eclipse IDE, it is also something like a framework - simple to change as user needs. Server should connect to MS SQL database to fetch data and pass that data to client and display those values in relevant text box in client desktop Application. REST client code to get the JTextField value.

 String id = this.jTextField1.getText();
 ObjectMapper mapper = new ObjectMapper();
        try {
              mapper.writerWithDefaultPrettyPrinter().writeValueAsString(id);
        } catch (JsonProcessingException ex) {
            Logger.getLogger(SearchOne_1.class.getName()).log(Level.SEVERE, null, ex);
        }

When I click the button, I want to pass that text field value to REST server. That part of the code not yet implemented and still finding a way to do it.

REST server code is like this. This is SQLtask.java .This is for select query.

    public SQLTasks(String dbSource) {
    super(dbSource);
}
public void SQLSelect(String SQL_SELECT) throws SQLException {

  try{
    stmt = conn.createStatement();  //connection created in MDBConnection class
    rs = stmt.executeQuery(SQL_SELECT);
  }
  catch(SQLException sqEx){
       System.out.println("SQL_EX "+sqEx);
       System.out.println("SQL_EX SELECT "+SQL_SELECT);
       throw new SQLException();

  }catch(Exception sqEx){
       System.out.println("EXC "+sqEx);
       System.out.println("EXC SELECT "+SQL_SELECT);
       throw new SQLException();
  }
}

This code is for DBAccess.java

public Employee getEmployeeDataByEPFNo(String dataSource,String EPFNo){
    SQLTasks st1 = new SQLTasks(dataSource);
    Employee employee=new Employee();
    try {
        st1.SQLSelect("SELECT * FROM Employee WHERE id="+EPFNo);
           ResultSet rs1 = st1.rs;
            while (rs1.next()) {


                employee.setEpfno(rs1.getString("EPFNo"));
                employee.setEfname(rs1.getString("fName"));
                employee.setElname(rs1.getString("lName"));
                employee.setDesignation(rs1.getString("designation"));
                employee.setNic(rs1.getString("NIC"));
                employee.setAddress(rs1.getString("Address"));
                employee.setArrival(rs1.getString("eArrivalDate"));
                employee.setDob(rs1.getString("DOB"));

            }
    } catch (SQLException e) {

        e.printStackTrace();
    }catch (Exception e) {

        e.printStackTrace();
    }
 return employee;
}

this is RESTServer.java

@GET
 @Path("/dbAccess/getDBValEmpByEPF/{EPFNo}")
 @Produces(MediaType.APPLICATION_JSON)

 public Employee getDBValEmpByEPF(@PathParam("EPFNo") String EPFNo) {
     Employee e= new Employee();
    DBAccess dbAcc=new DBAccess();
    e= dbAcc.getEmployeeDataByEPFNo("jdbc/db_sample_mssql","EPFNo");//call getEmployeeDataByEPFNo() which is inside DBAccess class
    return e;


    }

Instead manualy entering value as "500", what I want is pass that value getting from client. is it possible ?

You have used @PathParam for EPFNo in your rest service, so to get that value you need to pass EPFNo's value in your request url just like mentioned in below

http://localhost:8080/TestRestWebService/appPath/dbAccess/getDBValEmpByEPF/3245

Here 3245 is the EPFNo value which we passed to the server from client side and inside the getDBValEmpByEPF() method this will be available.

@GET
@Path("/dbAccess/getDBValEmpByEPF/{EPFNo}")
public Response getDBValEmpByEPF(@PathParam("EPFNo") String EPFNo) {
    System.out.println("EPFNo is="+EPFNo);//it will print EPFNo is=3245
       ......}

Sample client code

try {
        String EPFNo="234";//JTextField field value
        URL url = new URL(
                "http://localhost:8080/TestRestWebService/appPath/dbAccess/getDBValEmpByEPF/"+EPFNo);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Hope this will help you.

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