简体   繁体   中英

How to pass json from java to javascript function

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";                
  });

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

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));
});

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