There are four query values which I want to put in google chart value1 to value4. The problem is passing values from java to html. Under below I posted relevant codes.
Those
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['value1', **3**],
['value2', **2**],
['value3', **2**],
['value4', **2**]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
And this is java class.
public ResponseEntity<Map<String,Object>> status() {
Map<String,Object> map = new HashMap<String,Object>();
long countByXmlSuccessResult = statusRepository.countByXmlSuccessResult();
long countByXmlErrorResult = statusRepository.countByXmlErrorResult();
long countByJsonSuccessResult = statusRepository.countByJsonSuccessResult();
long countByJsonErrorResult = statusRepository.countByJsonErrorResult();
map.put("xml success:", **countByXmlSuccessResult**);
map.put("xml error:", **countByXmlErrorResult**);
map.put("json success:", **countByJsonSuccessResult**);
map.put("json error:", **countByJsonErrorResult**);
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
}
plus, html file path is under src/main/java folder and java file path is under src/main/resources folder.
You can expose that Java functionality as a service, and then make an ajax call to that service using jquery and finally grab the result and use it in your google chart code.
Ex:
Spring Boot:
#RestController
public class myHomeController{
...
#RequestMapping("/getValues")
public someDomainClass getMyValues(){
...
//someDomainClass is just a reg. pojo to store your values.
someDominClass class1 = new someDomainClass(value1, value2, value3
, value4);
return class1;
}
}
Your HTML file:
...
<script>
$.ajax({
url: "/getValues",
type: "GET",
success: function(result){
//result is a json object containing your values 1..4.
},
failure: functtion(err){...}
});
</script>
Best of luck :)
Related
I was trying for hours to send images from Angular to SpringBoot. Now I'm getting this error:
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
Frontend(Angular) code looks like this:
saveProduct(productSave: ProductSave, mainImg: File, imageList: File[]): Observable<any>
{
const formData = new FormData();
const formListData = new FormData();
formData.append('mainImg', mainImg, mainImg.name);
imageList.forEach( img => formListData.append('imageList', img));
return this.httpClient.post<ProductSave>(this.saveUrl, {productSave, mainImg, imageList});
}
mainImg and imageList are images uploaded from user, and initialized like so:
mainImg = event.target.files[0];
imageList.push(event.target.files[0]);
My backend (SpringBoot) code looks like this:
#PostMapping("/save")
public void saveProduct(#RequestBody ProductSave productSave, #RequestParam("mainImg")MultipartFile main, #RequestParam("imageList")MultipartFile[] multipartFiles)
{
System.out.println(productSave.getProduct().getName());
}
I really don't have idea how to send those images, I was trying to look around stack but I faild.
Thanks for any help!
The problem is in the Spring Boot Controller method Arguments.
In multipart request, you can send the JSON Request body. Instead, you will have to send, key-value pairs.
So, you have 2 ways to do what you want to do -
Send JSON String and then deserialize it.
Spring Boot API Sample :-
#PostMapping("/save")
public String create(#RequestPart("file")MultipartFile multipartFile, #RequestPart("files") List<MultipartFile> multipartFiles, #RequestPart("jsonString") String jsonString) {
/** To convert string to POJO
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
ProductSave productSave = this.objectMapper.readValue(jsonString,ProductSave.class); **/
return jsonString;
}
HTML/Javascript Sample: -
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="file" id="file">
<button onclick="submitData()">Submit Data</button>
<script type="text/javascript">
function submitData() {
const formData = new FormData();
const fileField = document.querySelector('input[id="file"]');
formData.append('jsonString', JSON.stringify({document: {data: 'value'}}));
formData.append('file', fileField.files[0]);
Array.from(fileField.files).forEach(f => formData.append('files', f));
fetch('http://localhost:8080/save', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
</body>
And in front end:-
JSON.stringify(product);
Send Files as Byte Arrays, You don't need to use form data in frontend in this case.
You can convert file object to byte arrays in frontend using:-
const fileToByteArray = async (file) => {
return new Promise((resolve, reject) => {
try {
let reader = new FileReader();
let fileByteArray = [];
reader.readAsArrayBuffer(file);
reader.onloadend = (evt) => {
if (evt.target.readyState === FileReader.DONE) {
const arrayBuffer = evt.target.result;
const array = new Uint8Array(arrayBuffer);
array.forEach((item) => fileByteArray.push(item));
}
resolve(fileByteArray);
};
} catch (e) {
reject(e);
}
});
};
in the application.properties try setting up the following -
spring.servlet.multipart.max-file-size=1024KB
spring.servlet.multipart.max-request-size=1024KB
spring.http.multipart.enabled=false
Play around with the max-file-size.
I am trying to populate highcharts chart using a csv file that I will generate in java back end and send to the from end using spring mvc.
First my controller class which I am almost positive is the issue but I don't know how to correctly send the csv file:
#Controller
public class ChartController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String indexHandler() {
return "index";
}
#RequestMapping(value = "/out", method = GET)
public String chartHandler() {
String fileName = "test.csv" //note: I have also tried moving this
//file to my WEB-INF location and it doesn't make a difference
InputParser input = new InputParser();
for (GenericDataObject gdo : input.getDataObjects()) {
CSVOutput.writeCSV(fileName,gdo);
}
return "index";
}
}
The csv file is successfully created as I intend so that's not an issue
here is my Java script for highcharts
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<some more high charts for font and color that I will leave out because its not currently being used>
</head>
<body>
<div id='container' style="width: 100%; height: 600px;"></div>
<script type="text/javascript">
$(document)ready.function() {
var groupId = [];
var date = [];
var val = [];
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'test'
},
xAxis: {
title: {
text: 'group and date'
},
categories: [groupId, date]
},
yAxis: {
title: {
text: 'data'
}
},
series: [{
data: val
}]
};
$.get('http://localhost:8080/web-data-app/out', function(data)) {
alert("success");
var lines = data.split('\n')
$.each(lines, function(lineNo, line) {
var items = line.split(',');
groupId.push(items[1]);
date.push(items[2]);
val.push(items[4]);
});
var cahrt = new Highcharts.Chart(options);
});
});
</script>
</body>
</html>
As of right now I get the outline of highcharts in my container, as well as the success alert so i know that much is working. however no data is being displaying withing the chart.
You can use httpResponse and send your content there. Like this
#RequestMapping(value = "/out", method = GET)
public void chartHandler(HttpServletResponse httpResponse) {
String fileName = "test.csv" //note: I have also tried moving this
//file to my WEB-INF location and it doesn't make a difference
InputParser input = new InputParser();
for (GenericDataObject gdo : input.getDataObjects()) {
CSVOutput.writeCSV(fileName,gdo);
}
httpResponse.setContentType("text/csv");
//you can use the output stream below to pass your content
httpResponse.getOutputStream()
}
I'm gong to making an autocompleter using jquery autocompleter. In my case I need to load some data from a method. That method(return a list) has a parameter and I need to pass the textfield input as the method argument. Is this possible? If it is how can I do this?
Method is,
public List<Item> getSuggestedData(String def) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select o from Item o WHERE o.itemName like :def");
q.setParameter("def", def + "%");
return q.getResultList();
} finally {
em.close();
}
}
index.jsp,
<script>
$(function() {
var availableTags = [/*I need to load data to here*/];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
<div class="ui-widget">
<s:textfield id="tags"/>
</div>
try this
$.ajax({
async:settings.Async,url:Url,cache:false,type:'POST',data:$("#tags").val()
}).done(function (result) {
$( "#tags" ).autocomplete({
source: result
});
});
jQuery is a client side script and java code is on server side. You need to send a HTTP request from client to the server to get your list of tags. You can do this by AJAX. jQuery has a good support for AJAX.
I want to pass textfield with id value pat to the getautocomplete.action in Struts 2. Here I am using TINY.box to pop up the next page.
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
T$('tiny_patient').onkeypress = function(){
TINY.box.show('getautocomplete.action',1,0,0,1)
}
</script>
You need to append the id pat and its value to the url that you pass to the show function. For example
var url = 'getautocomplete.action?pat=' + $("#pat").val();
You can then use the variable url in your show function.
You also need to add the following in your action class. This also depends on the java type of pat. I am using String,
private String pat;
public String getPat()
{
return pat;
}
public void setPat(final String value)
{
this.pat = value;
}
Note
It is recommended to get your url using the following instead of hard-coding the extension
<s:url id="url_variable" namespace="/namespace_of_action" action="action_name" />
var url = '<s:property value="url_variable" />?pat=' + $("#pat").val();
If you are trying to populate the box based on previous box selection or any server side process you have to use ajax.
In your action class , write a getter-setter for variable named "pat" like this:
private string pat;
public getPat()
{
.........
}
public setPat(String pat)
{
this.pat=pat;
}
and change
TINY.box.show('getautocomplete.action',1,0,0,1)
to
TINY.box.show('getautocomplete.action?pat="xyz"',1,0,0,1)
Hope this will solve your problem unless you have an idea about ajax.
Try
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
document.getElementById("tiny_patient").onkeypress = function(e){
TINY.box.show("<s:url action='getautocomplete'/>"+"?pat="+document.getElementById("pat").value,1,0,0,1)
}
</script>
I am new to Spring and web technology.
I have an table which contains a column with hyperlink. When I click on the hyperlink of a row, I need to display that rows data along with other details in a dialog. My controller method returns a ModelAndView which contains the data I need to show and the display page.
Problems:
How to show the dialog? and
How to pass the data to the dialog?
Table.jsp
<script type="text/javascript">
function showDialog(ref, date) {
$ajax({
type: "POST",
url: "/example/show.htm",
data: {
ref: ref,
date: date
}
success: function(data) {
},
error: function(data) {
}
});
}
</script>
Mapping
#RequestMapping(value = "show.htm", method=RequestMethod.POST)
public ModelAndView show(#RequestParam("ref") String ref, #RequestParam("date") String date,
HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
try {
SampleDTO SampleDTO = new SampleDTO();
sampleDTO.setDate(sdf.parse(date));
sampleDTO.setRef(ref);
SampleDTO billDto = // server call modelAndView.addObject("showBill", sampleDto);
modelAndView.setViewName("Dialog");
}
return modelAndView;
}
Your code is wrong, you are messing things, if you want to use jQuery and ajax calls then don't use ModelAndView in your Spring controller. Instead of that, use the following and return your bean or dto as a json using Jackson library from Java:
Include this jar in your lib project folder:
http://www.java2s.com/Code/JarDownload/jackson/jackson-all-1.9.9.jar.zip
Java code:
#RequestMapping(value = "businessBill.htm", method = RequestMethod.POST)
#ResponseBody
public String handleBusinessBillDetails(#RequestParam("reference") String billReference, #RequestParam("invoiceDate") String billDate,
HttpServletRequest request, HttpServletResponse response) {
String json = null;
try {
//1. Create 'jackson' object mapper
ObjectMapper objectMapper = new ObjectMapper();
BusinessBillDTO businessBillDTO = new BusinessBillDTO();
businessBillDTO.setBillDate(sdf.parse(billDate));
businessBillDTO.setBillReference(billReference);
BusinessBillDTO billDto = accountStatementBO.getBusinessBillDetails(businessBillDTO);
//2. Convert your 'bean' or 'dto' as 'json' string
json = objectMapper.writeValueAsString(billDto);
} catch (Exception ex) {
LOGGER.error(ex);
}
return json;
}
Then, in Table.jsp put the div used in Dialog.jsp as hidden, this will be your modal dialog in future (note that there are some changes in the span tags also):
<div id="BusinessBill" style="display:none;">
<h2>Bill Details</h2>
<em>Business Ltd</em>
<div class="row">
<span class="spanAsLabel">Account number</span>
<span id="dlg-account-number" class="spanAsLabel"></span>
</div>
<div class="row">
<span class="spanAsLabel">Bill date</span>
<span id="dlg-bill-date" class="spanAsLabel"></span>
</div>
</div>
Now fix your getBusinessBill(..) method like this:
You can also use $.ajax and maybe handle more states like onerror and others but this way is simpler (at least for me, you just need to evaluate if the returned data is null or not and let know the user - if null - that something happened at server side, maybe showing an alert with a generic message) - please read comments.
function getBusinessBill(billReference, billInvoiceDate) {
$.post("/AccountStatement/businessBill.htm", {
reference: billReference,
invoiceDate: billInvoiceDate
}, function (data) {
/* You can implement more validations for 'data', in my case I just used these 'if' conditionals but can vary. */
if(data != null) { //returned 'data' is not 'null'
/* parse 'data' as 'json' object
* will be good to console.log(data) and take a look. */
var obj = $.parseJSON(data);
if(obj != {}) { //check if 'data' is not an empty 'json' object once transformed
//set the 'data' in the dialog
$('#dlg-account-number').text(obj.accountNumber);
$('#dlg-bill-date').text(obj.billDate);
/* open modal dialog, you can simulate it this way (for this case)
* but the correct way is to use 'jquery-ui' dialog or any plugin you prefer.
* At this point you will see the hidden 'div' in a visible way with your 'data'.
*/
$('#BusinessBill').fadeIn();
} else {
//show 'generic' message
alert('No results found.');
}
} else {
//show 'generic' message
alert('An error occurred, try again.');
}
});
}
Finally, if everything is correct, you will see at the same page (Table.jsp) the modal dialog with your data, all made by an ajax call to avoid redirection pages like (Table.jsp to => Dialog.jsp).