How to populate drop down values using servlet response - java

I am able to have the response from a servlet and also able to show it on jsp page, but if I try to populate the same in a drop down, i am not able to-
Servlet code
String sql = "SELECT records from department";
ResultSet rs = s.executeQuery(sql);
Map<String, String> options = new LinkedHashMap<String, String>();
while (rs.next()) {
options.put(rs.getString("records"),rs.getString("records"));
}
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
JSP code---
JS code
<script type="text/javascript">
$(document).ready(function () { // When the HTML DOM is ready loading, then execute the following function...
$('.btn-click').click(function () { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('/testservlet', function (responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
//alert(responseJson);
var $select = $('#maindiv'); // Locate HTML DOM element with ID "someselect".
$select.find('option').remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function (key, value) { // Iterate over the JSON object.
$('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
});
</script>
HTML Code--
<input type="button" class="btn-click" id="best" value="check"/>
<div id="maindiv" style="display: block"></div>
If I create a <ul> and <li> I can have the data from the response on my page but not able to create the select options? Any help on this would be great.

Try it again after removing beginning /.
$.get('testservlet', function (responseJson)
The JSON string is not in proper way. It should be something like this. Why are you using JSON string here whereas you are passing only records as key as well as value.
Simply return a comma separated string from Servlet and split it jQuery.
Find example here for Iterating a comma separated string
Sample code:
var items = responseJson.split(',');
for ( var i = 0; i < items.length; i++) {
$('<option>').val(items[i]).text(items[i]).appendTo($select);
}

Related

How to return value from a jsp page

I have a jsp page which has java scriplets, and which is displaying the required output using out.println(obj), but I want to return this 'obj' so that these values can be used in another js file. How to return this from the jsp page?
So the js file is:
(function() {
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
var gridOptions = {
columnDefs: [
{headerName: 'CLIENT_ACRONYM', field: 'CLIENT_ACRONYM'},
{headerName: 'ORDER_QTY', field: 'ORDER_QTY'},
]
};
new agGrid.Grid(gridDiv, gridOptions);
jsonLoad( function(data) {
gridOptions.api.setRowData(data);
});
});
})();
function jsonLoad(callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '../output.json'); // by default async
xhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {
if(this.status == 200) {// onload called even on 404 etc so check the status
callback(this.response);
}
};
xhr.onerror = function() {
console.log('loading data error');
};
xhr.send();
}
JSP file returning Jsonarray:
JSONArray jsonArray = new JSONArray(orderDetailsList1);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArray);
So, instead of output.json in the js file I need to pass the JSOn Object returned by the jsp file. How to do that?
Use this code in jsp file
<input type="hidden" value="<%out.println(obj);%>" id="objValue"/>
In js file you can get the value by its id as
var objValue = document.getElementById("objValue");
Basically scriplets in jsp is not good.
Store in session scope or request scope and use it,like session.setAttribute('obj','value') in servlet and value="${obj}" in jsp.
Put that value in <div id=""> or <p id=""> tag which has ID in jsp and get that value in any js using getElementByID.

How to get this value into custom arraylist in servlet?

I have done this ajax code to send data from jsp to servlet.
My ajax code in jsp is as follows:
$(document).ready(function(){
$("#process").click(function(){
console.log($("#processlist").val());
$.ajax({
url: "processtimesheet.do",
type : 'POST',
data : {processlist : $("#processlist").val()},
success : function(response){
alert(response);
window.location.reload(true);
}
})
});
});
The value in JSP is getting picked from the below EL.
<input type="hidden" name="processlist" id="processlist" value="${timesheetList}">
I am getting the values in the servlet..
[com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16]
How do I convert these values back into List ?
If you right click and inspect near that hidden input element, you can see that input, in fact, has the value like com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16 . The data is unusable.
This means you embedded full object to the input field. You can instead use/embed any unique field of Timesheet type and return that list to servlet. Then you can identify which list is selected at server side.
Assuming you have id field in Timesheet class, construct an id list:
<input type="hidden" name="processlist" id="processlist" value="${timesheetIdList}">
And servlet:
Map<Integer, Timesheet> index = ...;// map (unique index) construction
List<Timesheet> listSelected = new ArrayList<>;
for(int i = 0; i<idarray.length; i++) {
if(index.containsKey(idarray[i])) {
listSelected.add(index.get(idarray[i]))
}
}

Redirecting to a JSP instead of the JSON response from a REST call

I am working on an assignment to create a simple blog, where a user can ask questions(posts) and answers can be given as comments.
With my limited knowledge on Java, REST and Jquery, I have managed to fetch the list of posts and am displaying them as a table.
Now whenever a user clicks on any post, he should be redirected to another page where the corresponding comments of the question can be displayed.
I have implemented a REST method in Java which returns the JSON response with the comments relevant to the post_id passed.
So whenever a user clicks on any post, he is redirected to a REST URL(.../services/comments?postID=1) and gets following response:
[
{
"postID": 1,
"commentID": 8,
"comment": "These are the answers getting added",
"commenterID": 7,
"commentDate": 1442671662000,
"commentVote": 0
}
]
Here is my JAVA method serving the REST call:
#GET
#Produces({ MediaType.APPLICATION_JSON })
public List<Comments> getUserComments(#QueryParam("postID") Integer postID) {
Session ses = HibernateUtil.currentSession();
ses.flush();
List<Comments> comments = null;
if(postID != null)
{
comments = ses.createQuery("select c from Comments c where c.postID="+postID+" order by c.commentDate desc").list();
}
HibernateUtil.closeSession();
return comments;
}
What is the "simplest" way to simultaneously redirect to a JSP where I can parse this JSON and display it?
You don't need to redirect the page to jsp.
What you need is a general template (jsp) of the page to display the post and its answers from the json. This page should make an ajax call to get the json for corresponding post (and its answers) and render it in the page.
Now the problem becomes how to do you pass the post id to this page.
You could do this by setting a non-html tag like this. <post_id id="post_id" value=1>. After the page is loaded the jquery will this tag (and extract the value attribute) to form the url for ajax call.
Example
Lets assume you have a page to display the list of all posts. This page will look like
post1
<br>
post2
Another jsp page to display the post and its comments. Lets call this post.jsp. This page should get a parameter post_id in the url. This page will set the tag <post_id> and use an ajax request to load the corresponding comments from REST url .../services/comments?postID="+post_id.
<body>
<script type="text/javascript">
$(document).ready(
function () {
//extract the post_id from tag value
var post_id = $("post_id").attr("value");
//form the rest url using post_id
var post_url = ".../services/comments?postID="+post_id;
$.ajax(
{
url: post_url,
success: function(data, status, jqXHR, json) {
json_data = JSON.parse(data);
html="";
for(var i=0; i<json_data.length; i++) {
//Comments rendering logic
html+= "<h5>"+json_data[i].comment +"</h5>";
}
$("#container").html(html);
}
}
);
}
);
</script>
<post_id value="<%= request.getParameter("post_id") %>" > </post_id>
<div id="container">
</div>
</body>

Jsoup - extracting variable value

I am parsing the html from the following webpage using Jsoup. How do I get the value from the variable price_ourBase:
<script type="text/javascript">
var price_ourBase = 279;
.
.
.
</script>
JS:
Element upperContainer_inner = document.select("div.upperContainer_inner").first();
Element table = upperContainer_inner.select("table.645.0.left.0.0").first();
Element script = table.select("script").first();
Element base_ourPrice = script.select("base_ourPrice").first();
price = (?, not sure what to put here or if there is more code needed).text();
I dont think jSoup can parse javascript like that. But, you could select the contents of the script with jSoup and then you could do something like
String[] result = script.toString().split(" ");
if(result[1].equals("price_ourBase"))
System.out.println("Our price is "+result[3].split(";")[0]);

how to get parameter values of json array in servlet that is sent from ajax

I want to send html table data using ajax to servlet so that I can save it to mysql database, therefore my question is, I prepared the html data as an array and sent it to servlet that is ok, but the problem is while in servlet How can i get each value to save it to database. this is my code.
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
script type="text/javascript">
$(document).ready(function () { //launch this code after the whole DOM is loaded
$("form").submit(function (event) { // function to process submitted table
var a={};
var tableData = []; // we will store rows' data into this array
$("#adminTable") // select table by id
.find(".tableRow") // select rows by class
.has(":checked") // select only rows with checked checkboxes
.each(function () { // for each selected row extract data
var tableRow = {};
var jRow = $(this);
tableRow.customerId = jRow.find('td.customerId').text();
tableRow.customerType = jRow.find('td.customerType').text();
tableRow.customerKWH = jRow.find('td.customerKWH').text();
tableRow.costomerKWD = jRow.find('input.name1').val();
tableData.push(tableRow);
//alert(tableRow.costomerKWD);
});
$.post(
"generateKwd", /*url of consuming servlet*/
{tableData: tableData}, /*data*/
function () {
alert("Success!");
}, /*function to execute in case of success*/
"json" /* data type */
);
event.preventDefault(); //Prevent sending form by browser
}
);
});

Categories

Resources