2

I make from my database a json string and i want to pass it to my javascript function, and print it into a html table. I use angular to make it easy to print the table, but i don't know how can i sent the data from java to javascript. These is what i tried in java.

public void jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
    Gson gson = new Gson();
    String json = gson.toJson(persoane);
    }

These is what i tried in javascript.

    var employeeApp = angular.module("EmployeeApp",[]);
    employeeApp.controller("empCtrl",function($scope){
    $scope.query = {}
    $scope.queryBy = '$'
    $scope.employees = [];
    $scope.orderProp="name";                
  });
2
  • 1
    So far you don't actually send anything, but using Gson for formatting is good enough. Commented Jun 8, 2017 at 12:40
  • So how can i sand the data, this is the problem for me, because i am a beginer and i don't know how to starte @M.Prokhorov Commented Jun 8, 2017 at 13:00

2 Answers 2

1

I do some changes in your code (you can apply whatever you like)

public ArrayList<PersoaneJSON> jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
   return persoane;
}

And here is Servlet doGet Method.

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            PrintWriter out = response.getWriter();


                response.setContentType("application/json;charset=utf-8");


                Gson gson = new Gson();
        String json = gson.toJson(jsonRetr("xyz"));

                out.write(json);
                out.close();

    }

Use jquery and read your json object as follows

$.getJSON( "Action/Servlet", function( data ) {
    console.log(JSON.parse(data));
});
Sign up to request clarification or add additional context in comments.

1 Comment

You can try java2s.com/Code/Jar/j/Downloadjsonsimple11jar.htm as well to parse your object to json.
0

You have to use a Java Servlet with WebMethod, so call that method which can return a JSON object containing data.

Example Java code:

ApplicationConfig.java

package example;
import java.util.Set;
import javax.ws.rs.core.Application;

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application

  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> resources = new java.util.HashSet<>();
    resources.add(QueryResource.class);
    return resources;
  }
}

QueryResource.java

package example;


@Path("query")
@Produces(MediaType.TEXT_PLAIN)
public class QueryResource {          

    @GET
    @Path("/employee")
    public String jsonRetr() throws Exception {
        ..
        return json;
    }
}

Now in js, inside your controller you can creater a function to connect to Servlet, passing $http Object to controller like $scope.

$http.get("http://localhost:8086/example/webresources/query/employee").success(function (data) {
                console.log(JSON.parse(data));
            }).error(function () {
                console.error('error');
            });

In your web.xml you have to setup a configuration like this:

<servlet-mapping>
    <servlet-name>RESTServlet</servlet-name>
    <url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>RESTServlet</servlet-name>        
   <servletclass>org.glassfish.jersey.servlet.ServletContainer</servletclass>
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>example.ApplicationConfig</param-value>
        </init-param>
        </servlet>

You need these dependencies:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.26-b01</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.26-b01</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>compile</scope>
 </dependency>

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.