output JSON array in a html table(a jsp page) - java
As the title suggested, how do I output a JSON array correctly in a table from a JSP page?
Right now whenever I display the JSON array object using <c:out value="${jsonArray}"/> but it just displays the whole contents of it in JSON string i.e {name: hello, address: baker street } but what I want to do is somehow parse this and display the info appropriately like this:
**name** **address**
hello baker street
spring java
tim sun
Is it possible in JSTL? I am new to JSTL stuff.
package com.kc.models;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
public class FileObject {
private String filename;
private String type;
private double size;
private Blob file;
private int id;
private String os;
private String description;
public FileObject() {
}
/**
* Constructor for use in returning just the list of files without the
* actual content
*
* #param name
* #param size
* #param id
* #param type
*/
public FileObject(String name, double size, int id, String type) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
}
/**
* Constructor used to create a fileObject with all its properties assigned
*
* #param name
* #param size
* #param id
* #param type
* #param file
*/
public FileObject(String name, double size, int id, String type, Blob file,
String os, String description) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
this.file = file;
this.os = os;
this.description = description;
}
public FileObject(String description){
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String fileName) {
this.filename = fileName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public Blob getFile() {
return file;
}
public void setFile(Blob file) {
this.file = file;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
#Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO call a method that returns a list of Mobile Apps.
String fileType = ServletRequestUtils.getRequiredStringParameter(request, "fileType");
//testAddingSomeFilesToDb();
return new ModelAndView("" + "testJsonResponse", "jsonArray",
getFileList(fileType) );
}
/**
* Get file list from sql server based on type
* #return file list in json
*/
private JSONArray getFileList(String type) {
// TODO: Get request parameter that states what type of file extensions
// the client wants to recieve
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
return file.getFileList(type);
}
public JSONArray getFileList(String type) {
return constructJsonArray(dbFileHelper.getFileList(type));
}
private JSONArray constructJsonArray(List<FileObject> fileList) {
JSONArray mJsonArray = new JSONArray();
JSONObject mJsonFileObject = new JSONObject();
for (int i = 0; i < fileList.size(); i++) {
mJsonFileObject.put("FileObject", fileList.get(i));
System.out.println("File ID = " + fileList.get(i).getId());
System.out.println("fileName = " + fileList.get(i).getFilename());
System.out.println("type = " + fileList.get(i).getType());
System.out.println("size = " + fileList.get(i).getSize());
mJsonArray.add(mJsonFileObject);
}
return mJsonArray;
}
here is my jsp page:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var files = "${jsonArray}";
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(files).each(function(i, file) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(file.filename))
.append($('<td/>').text(file.id))
.append($('<td/>').text(file.type))
.append($('<td/>').text(file.size))
.append($('<td/>').text(file.os));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
edit: here is my json output:
var files = [{"FileObject":{"description":"","file":null,"filename":"ACG Simulator(firefox).jpg","id":6,"os":"","size":172,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"car.jpg","id":11,"os":"","size":152,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted.jpg","id":13,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted2.jpg","id":14,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts options.jpg","id":15,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"edit contact view.jpg","id":17,"os":"","size":52,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"fileObject.jpg","id":20,"os":"","size":30,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"groups.jpg","id":27,"os":"","size":31,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"inside contacts.jpg","id":31,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Music highlighted.jpg","id":37,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music options view.jpg","id":38,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music phone view.jpg","id":39,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music vault view.jpg","id":40,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"nice.jpg","id":41,"os":"","size":225,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo highlighted.jpg","id":42,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo options view.jpg","id":43,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo preview view.jpg","id":44,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos phone view.jpg","id":45,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos vault view.jpg","id":46,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"svn error.jpg","id":54,"os":"","size":35,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Video Highlighted.jpg","id":55,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Videos options view.jpg","id":56,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos phone view.jpg","id":57,"os":"","size":50,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos Vault view.jpg","id":58,"os":"","size":49,"type":"jpg"}}]
Your question is too ambigious to give a suitable answer, so I'll cover all possible scenarios:
You have it as a JavaScript variable like so:
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
I'd suggest to use jQuery to create a HTML table out of it. Here's an SSCCE, you can copy'n'paste'n'run it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(persons).each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
You have it as a Java String variable like so:
String jsonPersons = "["
+ "{ \"name\": \"John Doe\", \"address\": \"Main Street 1\" },"
+ "{ \"name\": \"Jane Doe\", \"address\": \"Baker Street 1\" },"
+ "{ \"name\": \"Jack Doe\", \"address\": \"Church Street 1\" }"
+ "]";
Then I suggest to use a JSON parser to get a List<Person> out of it, like Google Gson:
List<Person> persons = new Gson().fromJson(jsonPersons, new TypeToken<List<Person>>() {}.getType());
Where the Person class look like this:
public class Person {
private String name;
private String address;
// Add or generate getters/setters.
}
Let the servlet put it in the request scope and forward to JSP for display like so:
request.setAttribute("persons", persons);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
In JSP, use JSTL <c:forEach> to iterate over it:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${persons}" var="person">
<tr>
<td>${person.name}</td>
<td>${person.address}</td>
</tr>
</c:forEach>
</table>
Same as 2), you have it as a Java variable, but you'd like to obtain it by Ajax in JSP. Then create a Servlet class which does the following in doGet() method:
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(jsonPersons);
And call it by jQuery Ajax with a callback which does the same as 1).
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$.getJSON('url/to/servlet', function(persons) {
persons.each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
});
Assuming:
jsonArray = [ {name: 'hello', address: 'baker street'}, ... ];
One way to do it is to construct the html in Javascript code like this:
var myHTMLStr = '<table>';
for(var i in jsonArray) {
myHTMLStr+='<tr><td>' + jsonArray[i]['name'] + '</td><td>' + jsonArray[i]['address'] + '</td></tr>';
}
myHTMLStr+='</table>';
Now display the HTML string:
document.getElementById('tableOutput').innerHTML = myHTMLStr;
Related
How to parse a JSONString and turn its values into an Array?
How to parse a JSONString, from a once JSONString.stringify simple array that now "appears flattened" inside, and turn its values back into a Java List or Java Array? (Using Jersey 1.x & Java) ? Array originally started as [1,2,3] before it was stringify-ed. items = (3) [" To", "8357", "30028"] --> JSON.stringify(items) sent through rest call Chrome Dev Tools's Request Payload after rest call: items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D /*inside (Jersey) Rest Resource #POST #Path("/...") #Consumes(MediaType.APPLICATION_JSON) #Produces(MediaType.APPLICATION_JSON) public Response receive(#Context SecurityContext securityContext, #Context HttpServletRequest srequest, String jsonString) throws URISyntaxException, JSONException ... /*eclipse watch on jsonString inside (Jersey) Rest Resource items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D */[enter image description here][2] NOTE: There is no name value. There is no entity. There's only a very simple string of IDs because that's all I need. (Is that supported by Jersey 1.X or JAX-RS 1.X?) JSONArray jSONArray = new JSONArray(java.util.Arrays.asList(jsonString)); Eclipse jSONArray Expression: jSONArray --myArrayList ----elementData ------[0] "items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D" ----------value ------------[0..99] ---------------[0] i ---------------1 t ---------------[2] e ---------------[3] m ---------------[4] s ---------------[5] = ---------------[6] % ---------------[7] 5 ---------------[8] B ....
I cannot understand exactly your original question, but one of the way is: import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JFileChooser; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JsonParser { JFileChooser chooser = new JFileChooser(); File f; static String fn = ""; static String js1 = "{\"name\": \"LALA\", \"email\": \"tst#tst.com\"}"; String name = "name"; String email = "email"; String fName = "firsName"; String city = "city"; // ... other needed fields User u1 = null; public JsonParser() { parseFile(); System.out.println("\n" + u1.toShortString()); } private String openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception { int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { f = chooser.getSelectedFile(); } return f.getAbsolutePath(); } // To parse JSON files with data //=========================================== public void parseFile() { JSONParser parser = new JSONParser(); try { // To parse obj 1 Object obj1 = parser.parse(js1); System.out.println("User 1: " + obj1.toString()); System.out.println(); JSONObject jobj1 = (JSONObject) obj1; String from_name = jobj1.get(name).toString(); String from_email = jobj1.get(email).toString(); // String from_fName = jobj1.get(fName).toString(); // String from_city = jobj1.get(city).toString(); u1 = new User(from_name, from_email, null, null); // System.out.println(u1.toString() + "\n"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new JsonParser(); } class User { String name = null; String email = null; String fName = null; String city = null; public User(String n, String e, String f, String c) { this.name = n; this.email = e; this.fName = f; this.city = c; } public String getFirsName() { return this.name; } public String setFirsName(String s) { return this.name = s; } public String getEmail() { return this.email; } public String setEmail(String s) { return this.email = s; } public String toString() { return "{\"name\":" + this.name + ", " + "\"email\":" + this.email + ", " + "\"firsName\":" + this.fName + ", " + "\"city\":" + this.city + "\"}"; } public String toShortString() { return "{\"name\": \"" + this.name + "\", " + "\"email\": \"" + this.email + "\"}"; } }; } OUTPUT: User 1: {"name":"LALA","email":"tst#tst.com"} {"name": "LALA", "email": "tst#tst.com"}
Thanks guys. I managed to find an alternative send & receive: now sending array without stringify-ing it first receiving with: public Response archiveSelectedApplicants(#Context SecurityContext securityContext, #Context HttpServletRequest srequest, #FormParam("items[]") List items) throws URISyntaxException
Parsing JSON file
I'm trying to parse the below given json. { "sections": [ { "title": "Title android", "level": 1, "content": [ { "type": "paragraph", "text": "This is paragraph 1 for android." } { "type": "paragraph", "text": "This is paragraph 2 for android" } ], "images": [ { "src": "http://image1 android.", "caption": "Image 1." }, { "src": "http://image2 android", "caption": "Image 2." } ] }, { "title": "Title java", "level": 2, "content": [ { "type": "paragraph", "text": "This is paragraph 1 for Java." }, { "type": "paragraph", "text": "This is paragraph 2 for Java" } ], "images": [ { "src": "http://image1 java.", "caption": "Image 1." }, { "src": "http://image2 java", "caption": "Image 2." } ] }, { "title": "Title json", "level": 3, "content": [ { "type": "paragraph", "text": "This is paragraph 1 for Json." }, { "type": "paragraph", "text": "This is paragraph 2 for Json" }, { "type": "paragraph", "text": "This is paragraph 3 for Json" } ], "images": [ { "src": "http://image1 Json.", "caption": "Image 1." }, { "src": "http://image2 Json", "caption": "Image 2." } ] } I want to output these Json as Title 1 :Title android. \n Content 1:This is paragraph 1 for android. This is paragraph 2 for android. Image 1:http:// image1 android. Image 2:http:// image2 android. Title :Title Java. Content:This is paragraph 1 for Java. This is paragraph 2 for Java. Image 1:http:// image1 Java. Image 2:http:// image2 Java. ... and so on. What I have done so far public class ParseJSON { public static String[] titles; public static String[] contents; public static String[] levels; public static final String JSON_ARRAY = "sections"; public static final String TITLE = "title"; public static final String CONTENT = "content"; public static final String TEXT = "text"; private JSONArray sections = null; private JSONArray content = null; private String json; public ParseJSON(String json) { this.json = json; } protected void parseJSON() { JSONObject jsonObject ; try { jsonObject = new JSONObject(json); sections = jsonObject.getJSONArray(JSON_ARRAY); titles = new String[sections.length()]; levels = new String[sections.length()]; for (int i = 0; i < sections.length(); i++) { titles[i] = sections.getJSONObject(i).getString(TITLE); JSONArray content = sections.getJSONObject(i).getJSONArray(CONTENT); contents = new String[content.length()]; Log.d("MainActivity",contents.toString()); for (int j = 0; j < content.length(); j++) { contents[j] += content.getJSONObject(j).getString(TEXT).toString() + "\n\n"; //Log.d("MainActivity",contents.toString()); } } } catch (JSONException e) { e.printStackTrace(); } } } The above code is not complete. I want to print the json as above. But I'm not getting the title part and paragraph part as needed. When I parse the TEXT from content array it gives all the paragraphs combined from the json as content[0],content[1] and so on. But I want contents with respect to titles only I think the link part plays some role,but I don't know how. UPDATE What if I want the output as the middle one alone.ie, //android title part //not needed //The part needed is below one: Title :Title Java. Content:This is paragraph 1 for Java. This is paragraph 2 for Java. Image 1:http:// image1 Java. Image 2:http:// image2 Java. //json title part //not needed
Why do you torture yourself by manually parse JSON? May I recommend you to use some lightweight JSON Parser. This is how I do that in Android with org.codehaus.jackson mapper: package yourpackage; import java.io.IOException; import java.io.StringWriter; import java.util.List; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JsonMapper { private static ObjectMapper objectMapper = new ObjectMapper(); public static Object fromJsonToJavaObject(String jsonObject, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException { return objectMapper.readValue(jsonObject, clazz); } public static String fromJavaObjectToJson(Object javaObject) throws JsonGenerationException, JsonMappingException, IOException { StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, javaObject); return stringWriter.toString(); } public static List<?> fromJsonToJavaObjects(String jsonObject, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException { return objectMapper.readValue(jsonObject, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); } } For your case, just pass the JSON string and the expected result type to the first method like TitleWithImages.class. This would be the Maven dependency (but you are using Android studio): <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
try { JSONObject jsonObject = new JSONObject(data); sections = jsonObject.getJSONArray("sections"); for (int i = 0; i < sections.length(); i++) { JSONObject contentJSON = sections.getJSONObject(i); Log.d("", "Title: "+ contentJSON.getString("level") + " " + contentJSON.getString("title") ); JSONArray contentArray = contentJSON.getJSONArray("content"); Log.d("","Content: " + contentJSON.getString("level") + " " ); for (int j = 0; j < contentArray.length(); j++) { Log.d("",contentArray.getJSONObject(i).getString("text")); } JSONArray imageArray = contentJSON.getJSONArray("images"); Log.d("","Images: " + contentJSON.getString("level") + " " ); for (int j = 0; j < imageArray.length(); j++) { Log.d("",imageArray.getJSONObject(j).getString("src")); } } } catch (JSONException e) { e.printStackTrace(); } I have printed the output on Logcat you can just add it in string arrays or better create object with parameters you need
Using the json converter to pojo tool like this, you can generate Plain Old Java Objects (POJO) that you can use to easily manipulate your json results. From your json string, I was able to generate the following Java classes: public class Content { #SerializedName("type") #Expose private String type; #SerializedName("text") #Expose private String text; /** * * #return * The type */ public String getType() { return type; } /** * * #param type * The type */ public void setType(String type) { this.type = type; } /** * * #return * The text */ public String getText() { return text; } /** * * #param text * The text */ public void setText(String text) { this.text = text; } } Then this represents the Image entity: public class Image { #SerializedName("src") #Expose private String src; #SerializedName("caption") #Expose private String caption; /** * * #return * The src */ public String getSrc() { return src; } /** * * #param src * The src */ public void setSrc(String src) { this.src = src; } /** * * #return * The caption */ public String getCaption() { return caption; } /** * * #param caption * The caption */ public void setCaption(String caption) { this.caption = caption; } } This is the umbrella that contains the two objects as lists: public class Section { #SerializedName("title") #Expose private String title; #SerializedName("level") #Expose private int level; #SerializedName("content") #Expose private List<Content> content = new ArrayList<Content>(); #SerializedName("images") #Expose private List<Image> images = new ArrayList<Image>(); /** * * #return * The title */ public String getTitle() { return title; } /** * * #param title * The title */ public void setTitle(String title) { this.title = title; } /** * * #return * The level */ public int getLevel() { return level; } /** * * #param level * The level */ public void setLevel(int level) { this.level = level; } /** * * #return * The content */ public List<Content> getContent() { return content; } /** * * #param content * The content */ public void setContent(List<Content> content) { this.content = content; } /** * * #return * The images */ public List<Image> getImages() { return images; } /** * * #param images * The images */ public void setImages(List<Image> images) { this.images = images; } } After generating them and saving in your project like any other class, you can now use Gson to convert your json String into these objects with properties. Since you get a List of Sections in your json response, what you can do is simple: List<Section> sections = new Gson().fromJson(jsonString, Section.class); Now you have a list of sections that you can loop through to obtain images and content. Content, remember, has a list of its own, just like images do. From that you should be able to easily get your data. I hope this helps you. You can use Gradle to add Gson or download the jar file and add to your /libs folder in android studio.
Display datatable on clicking a button
I'm writing a webapp where in there is a table that is to be generated using Ajax. This data is actually pulled from the database. And here I want to use jquery datatable plugin. Index.jsp <html> <head> </head> <body> <marquee> <h1>This is an example of ajax</h1> </marquee> <form name="vinform"> Enter id:<input type="button" id="somebutton" value="Click Me"> </form> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Case Number</th> <th>Case Owner</th> <th>Status</th> <th>Issue</th> <th>Reason</th> <th>Date/Time Opened</th> <th>Age</th> </tr> </thead> <tfoot> <tr> <th>Case Number</th> <th>Case Owner</th> <th>Status</th> <th>Issue</th> <th>Reason</th> <th>Date/Time Opened</th> <th>Age</th> </tr> </tfoot> </table> <span id="somediv"> </span> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript" src="tableGenerator.js"></script> </body> </html> tableGenerator.js $('#somebutton').click(function() { $(document).ready(function() { $('#example').DataTable({ "ajax" : "Controller", "columns" : [ { "data" : "userBean.caseNumber" }, { "data" : "userBean.caseOwner" }, { "data" : "userBean.status" }, { "data" : "userBean.issue" }, { "data" : "userBean.reason" }, { "data" : "userBean.age" } ] }); }); }); UserBean.java package org.bean; public class UserBean { private int age; private String caseOwner, status, issue, reason, dateOpened, caseNumber, resolution, finalStatus, startDate, endDate; private Double totalTimeTaken; public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getCaseNumber() { return caseNumber; } public void setCaseNumber(String caseNumber) { this.caseNumber = caseNumber; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCaseOwner() { return caseOwner; } public void setCaseOwner(String caseOwner) { this.caseOwner = caseOwner; } public String getStatus() { return status; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public void setStatus(String status) { this.status = status; } public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } public String getDateOpened() { return dateOpened; } public void setDateOpened(String dateOpened) { this.dateOpened = dateOpened; } public String getResolution() { return resolution; } public void setResolution(String resolution) { this.resolution = resolution; } public String getFinalStatus() { return finalStatus; } public void setFinalStatus(String finalStatus) { this.finalStatus = finalStatus; } public double getTotalTimeTaken() { return totalTimeTaken; } public void setTotalTimeTaken(Double totalTimeTaken) { this.totalTimeTaken = totalTimeTaken; } public UserBean() { } public UserBean(String caseNumber, String caseOwner, String issue, int age, String reason, String dateOpened, String status, String finalStatus, String resolution, String startDate, String endDate, Double totalTimeTaken) { this.caseNumber = caseNumber; this.caseOwner = caseOwner; this.issue = issue; this.reason = reason; this.age = age; this.dateOpened = dateOpened; this.status = status; this.resolution = resolution; this.finalStatus = finalStatus; this.startDate = startDate; this.endDate = endDate; this.totalTimeTaken = totalTimeTaken; } } Controller.java(Servlet) import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.bean.UserBean; import com.dao.DataDao; import com.google.gson.Gson; #WebServlet("/Controller") public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // String id = request.getParameter("val"); DataDao dataDao = new DataDao(); ArrayList<UserBean> list = dataDao.getFrameWork(); String searchList = new Gson().toJson(list); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(searchList); } catch (Exception e) { System.err.println(e.getMessage()); } } } DBUtility.java package com.dao; import java.sql.Connection; import java.sql.DriverManager; public class DBUtility { private static Connection connection = null; public static Connection getConnection() throws Exception { if (connection != null) return connection; else { // Store the database URL in a string String userName = "sa"; String password = "T!ger123"; String url = "jdbc:sqlserver:XXXXXX;DatabaseName=TEST"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // set the url, username and password for the databse connection = DriverManager.getConnection(url, userName, password); return connection; } } } DataDao.java package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import org.bean.UserBean; public class DataDao { private Connection connection; public DataDao() throws Exception { connection = DBUtility.getConnection(); } public ArrayList<UserBean> getFrameWork() throws SQLException { ArrayList<UserBean> list = new ArrayList<UserBean>(); PreparedStatement ps = null; try { ps = connection.prepareStatement("select * from statusTable"); // ps.setString(1, frameWork); ResultSet rs = ps.executeQuery(); while (rs.next()) { UserBean userBean = new UserBean(); userBean.setCaseNumber(rs.getString(1)); userBean.setCaseOwner(rs.getString(2)); userBean.setStatus(rs.getString(3)); userBean.setIssue(rs.getString(4)); userBean.setReason(rs.getString(5)); userBean.setDateOpened(rs.getString(6)); userBean.setAge(rs.getInt(7)); list.add(userBean); } } catch (Exception e) { System.out.println(e.getMessage()); } return list; } } When I click on the button, instead of displaying the table data, it is showing nothing apart from the Basic html skeleton created in my index file. Instead of using $('#somebutton').click(function() { $(document).ready(function() { $('#example').DataTable({ "ajax" : "Controller", "columns" : [ { "data" : "userBean.caseNumber" }, { "data" : "userBean.caseOwner" }, { "data" : "userBean.status" }, { "data" : "userBean.issue" }, { "data" : "userBean.reason" }, { "data" : "userBean.age" } ] }); }); }); when i used $('#somebutton').click( function() { $.getJSON('Controller', function(searchList) { var $table = $('<table>').appendTo($('#somediv')); $.each(searchList, function(index, userBean) { $('<tr>').appendTo($table).append( $('<td>').text(userBean.caseNumber)).append( $('<td>').text(userBean.caseOwner)).append( $('<td>').text(userBean.status)).append( $('<td>').text(userBean.issue)).append( $('<td>').text(userBean.reason)).append( $('<td>').text(userBean.age)); }); }); }); A normal html table is getting displayed. Please let me know how can i display this data. Thanks
No suitable HttpMessageConverter found for response type - Custom RestTemplate
First, sorry for possible duplicate. I found some questions regarding to similar problems. However, I still can't figure out what's wrong in my specific case. So, example json from server: [ { "_id": "55f9690f30ef6f210e2dc3a5", "ID": "74c4bf82-9f78-4df5-b9d7-6547e2a55eaa", "Name": "myLand, Saarbrücken", "__v": 0, "Shops": [ { "ID": "b8eacee1-b2c6-48aa-ac6f-2e7fbe3a5d68", "Name": "ARA", "_id": "55f9690f30ef6f210e2dc3a6", "News": [ { "ID": "d79b7f51-7d5c-4bd6-9321-e40c6e93788c", "ValidFrom": "2015-01-08T00:00:00", "ValidTo": "2015-09-30T00:00:00", "_id": "55f9690f30ef6f210e2dc3a7", "Texts": [ { "ID": "TITLE", "Value": "11. Wochenspiegel Firmenlauf", "_id": "55f9690f30ef6f210e2dc3a9" }, { "ID": "BODY", "Value": "Wir gratulieren zur ersten und gleich sehr erfolgreichen Teilnahme am 11.Wochenspiegel Firmenlauf in Dillingen,\r\nunsere Teams vom “Outlet center Wadgassen“ haben ihren Lauf mit tollen Zeiten abgeschlossen und hatten trotz\r\nhohen Temperaturen einen wunderbaren Tag – wie man sehen kann. Wir freuen uns schon jetzt auf nächstes Jahr!", "_id": "55f9690f30ef6f210e2dc3a8" } ] } ], "Texts": [ { "ID": "DESCRIPTION", "Value": "Mit Tradition in die Zukunft Seit sechs Jahrzehnten steht ara für vielfältige Schuhmode erstklassiger Qualität,", "_id": "55f9690f30ef6f210e2dc3aa" } ] } ] } ] I generated class called Mall (and all subclasses for the rest of data structure): public class Mall { private String Id; private String ID; private String Name; private int V; private List<Shop> Shops = new ArrayList<Shop>(); private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * #return The Id */ public String getId() { return Id; } /** * #param Id The _id */ public void setId(String Id) { this.Id = Id; } /** * #return The ID */ public String getID() { return ID; } /** * #param ID The ID */ public void setID(String ID) { this.ID = ID; } /** * #return The Name */ public String getName() { return Name; } /** * #param Name The Name */ public void setName(String Name) { this.Name = Name; } /** * #return The V */ public int getV() { return V; } /** * #param V The __v */ public void setV(int V) { this.V = V; } /** * #return The Shops */ public List<Shop> getShops() { return Shops; } /** * #param Shops The Shops */ public void setShops(List<Shop> Shops) { this.Shops = Shops; } public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } Server returns conent-type text/plain. To modify content type, I wrote simple extend class: public class RestTemplateJSON extends RestTemplate { #Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { //logger.info(RestTemplateJSON.class.getSuperclass().getSimpleName() + ".doExecute() is overridden"); Assert.notNull(url, "'url' must not be null"); Assert.notNull(method, "'method' must not be null"); ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); // Set ContentType to JSON response.getHeaders().setContentType(MediaType.APPLICATION_JSON); if (!getErrorHandler().hasError(response)) { logResponseStatus(method, url, response); } else { handleResponseError(method, url, response); } if (responseExtractor != null) { return responseExtractor.extractData(response); } else { return null; } } catch (IOException ex) { throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + url + "\":" + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } } private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response) { //if (logger.isDebugEnabled()) { try { System.out.println(method.name() + " request for \"" + url + "\" resulted in " + response.getRawStatusCode() + " (" + response.getStatusText() + ")"); } catch (IOException e) { // ignore } } } private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException { getErrorHandler().handleError(response); } } Finally, this is how I'm trying to consume my webservice: RestTemplateJSON restTemplate = new RestTemplateJSON(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); Mall mall = restTemplate.getForObject(url, Mall.class); However, I'm still getting the same exception: Could not extract response: no suitable HttpMessageConverter found for response type [m.m.restspringtest.Mall.Mall] and content type [application/json] As far as I know, if I change content type, it should be ok. Can you please tell me what am I doing wrong?
So, I finally figured it out. There is array in json, so I want to map it to Mall[], not Mall. I provided wrong class, there should be: RestTemplateJSON restTemplate = new RestTemplateJSON(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); Mall[] malls = restTemplate.getForObject(url, Mall[].class);
Transferring data from servlet to jsp page
I would like to get rid of the printWriter code in the servlet. Basically I want to output the current customers and their respective cities with the id which is a hidden field on the index page. From there I would like to be able to edit the customer name or city and then have it sent back to the index page where the information would be updated. How do I do this? Servlet package edu.witc.Assignment02.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.witc.Assignment02_model.*; /** * Servlet implementation class CustomerServlet */ #WebServlet(name = "CustomerServlet", urlPatterns = { "/customer", "/editCustomer", "/updateCustomer" }) public class CustomerServlet extends HttpServlet { private static final long serialVersionUID = -20L; private List<Customer> customers = new ArrayList<Customer>(); /** * #see HttpServlet#HttpServlet() */ public CustomerServlet() { super(); // TODO Auto-generated constructor stub } #Override public void init() throws ServletException { Customer customer1 = new Customer(); customer1.setId(1); customer1.setName("Donald D."); customer1.setCity("Miami"); customer1.add(customer1); Customer customer2 = new Customer(); customer1.setId(2); customer1.setName("Mickey M."); customer1.setCity("Orlando"); customer1.add(customer2); } private void sendCustomerList(HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><head><title>Customers</title></head>" + "<body><h2>Custoemrs</h2>"); writer.println("<ul>"); for (Customer customer : customers){ writer.println("<li>" + customer.getName() + "(" + customer.getCity() + ") (" + "<a href='editCustomer?id=" + customer.getId() + ";>edit</a>)"); } writer.println("</ul>"); writer.println("</body></html>"); } private Customer getCustomer(Integer customerId){ for (Customer customer : customers) { if(customer.getId() == customerId){ return customer; } } return null; } private void sendEditCustomerForm(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); Integer customerId = 0; try{ customerId = Integer.parseInt(request.getParameter("id")); }catch(NumberFormatException e){ } Customer customer = getCustomer(customerId); if(customer != null){ writer.println("<html><head>" + "<title>Edit Customer</title></head>" + "<body><h2>Edit Customer</h2>" + "<form method = 'post' action = 'updateCustomer'>"); writer.println("<input type = 'hidden' name = 'id' value = 'customerId'/>"); writer.println("<table>"); writer.println("<tr><td>Name:</td><td>" + "<input name = 'name' value = '" + customer.getName().replaceAll("'", "'") + "'/></td></tr>"); writer.println("<tr><td>City:</td><td>" + "<input name = 'city' value = '" + customer.getCity().replaceAll("'", "'") + "'/></td></tr>"); writer.println("<tr>" + "<td colspan='2' style = 'text-align: right'>" + "<input type ='submit' value = 'Update'/></td>" + "</tr>"); writer.println("<tr><td colspan='2'>" + "<a href = 'customer'>CustomerList</a>" + "</td></tr>"); writer.println("</table>"); writer.println("</form></body>"); }else{ writer.println("No Customer Found"); } } #Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); if(uri.endsWith("/customer")){ sendCustomerList(response); }else if(uri.endsWith("/editCustomer")){ sendEditCustomerForm(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //update customer Integer customerId = 0; try{ customerId = Integer.parseInt(request.getParameter("id")); }catch(NumberFormatException e){ } Customer customer = getCustomer(customerId); if(customer != null){ customer.setName(request.getParameter("name")); customer.setCity(request.getParameter("city")); } sendCustomerList(response); } } Customer Class package edu.witc.Assignment02_model; public class Customer { private Integer id; private String name; private String city; public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String getCity(){ return city; } public void setCity(String city){ this.city = city; } public void add(Customer customer1) { // TODO Auto-generated method stub } } index page <%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Home</title> </head> <body> <h1>Current Customer(s) w/City</h1><br> <%! String name, city; %> <% %> </body> </html>
Better late than never. Ok, to get this working you should add jstl library to your project. Servlet #WebServlet(name = "CustomerServlet", urlPatterns = { "/customer", "/editCustomer", "/updateCustomer" }) public class CustomerServlet extends HttpServlet { private static final long serialVersionUID = -20L; private List<Customer> customers = new ArrayList<Customer>(); #Override public void init() throws ServletException { Customer customer1 = new Customer(); ... customers.add(customer1); Customer customer2 = new Customer(); ... customers.add(customer2); } private Customer getCustomer(Integer customerId){ for (Customer customer : customers) { if(customer.getId() == customerId){ return customer; } } return null; } #Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); if(uri.endsWith("/customer")){ request.setAttribute("customers", customers); request.getRequestDispatcher("/customers.jsp").forward(request, response); }else if(uri.endsWith("/editCustomer")){ try{ customerId = Integer.parseInt(request.getParameter("id")); }catch(NumberFormatException e){ e.printStackTrace(); } Customer customer = getCustomer(customerId); request.setAttribute("customer", customer); request.getRequestDispatcher("/edit_customer.jsp").forward(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Integer customerId = 0; try{ customerId = Integer.parseInt(request.getParameter("id")); }catch(NumberFormatException e){ } Customer customer = getCustomer(customerId); if(customer != null){ customer.setName(request.getParameter("name")); customer.setCity(request.getParameter("city")); } response.sendRedirect("/customer"); } } customers.jsp <%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %> <%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <h1>Customer list</h1> <ul> <c:forEach var="c" items="${customers}"> <li>${c.name} (Edit)</li> </c:forEach> </ul> edit_customer.jsp <%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %> <%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <h1>Edit customer</h1> <form method="POST" action="/updateCustomer"> <input type="hidden" name="id" value="${customer.id}"/> Name: <input type="text" name="name" value="${customer.name}"/><br/> City: <input type="text" name="city" value="${customer.city}"/><br/> <input type="submit" value="Save"/> </form>