Spring MVC upload file and send parsed data back - java

I'm using Spring MVC for my web application. I'm implementing the file upload functionality. Following the tutorial, I was able to send the uploaded file to server through submit action of input type of "file". Then I parsed the uploaded xls file at server side and need to send parsed data (3 lists of custom objects) back to the same form to display. I sent the data back through ModelAttribute.
However, my problem now is that on the client side, I need to use those lists of custom objects in my javascript, but I can only retrieve each field of the custom objects through jstl tag library but I cannot get those custom objects in my javascript where I need them for other logic implementation.
Then I have tried an Ajax file upload plug-in because ajax call can return JSON response which objects can be used in Javascript. But cannot get the plug-in work properly.
I have been stuck on this problem for several days>.< Can anybody help on this? Either a solution on using ModelAttribute in Javascript or a Ajax call solution is ok. Thank you very much!!!

Is there any reason why you can't simply "flatten" your model objects into HTML and then access them from Javascript using the DOM API?
You said you return 3 lists of custom objects. So how about for each list, you build up a (hidden) HTML table, for example if you have a list of Person objects in a ModelAttribute called people:
<table id="people-table">
<c:forEach var="person" items="${people}">
<tr id="${person.id}>
<td class="person-name">${person.name}</td>
<td class="person-age">${person.age}</td>
<td class="person-height">${person.height}</td>
</tr>
</c:forEach>
</table>
Now in your Javascript, you iterate over the rows in people-table, doing whatever you need to do - for example using jQuery:
$("#people-table tr").each(
var personId = $(this).attr("id");
var personName = $(this).find("td.person-name").text();
// etc, etc
// Do something with these as required
);
It's possibly not the most elegant solution but it's easy to debug at least - you can always just inspect the table with Firebug etc to see if the data is correct, and from there you'll know whether to continue debugging the server-side or in the Javascript.

Related

Migrating app to AngularJS?

i have existing web application where most of the time pages are submitted traditional way(like document.form.submit or )
I am planning to migrate to angularJS which i am learning. I am not sure how we can submit form in traditional way (without ajax) with angularJS ?
I know it won't be true Single Page App(SPA), but for starting i would like to go this way.
Approach for migrating traditional app to SPA :-
In future , i would like to go for SPA in which i will submitting the form thru ajax way using AngularJS. I have vague understanding
how will i approach this but would like to get experts advice on this.
My Understanding:-
Say i land to welcome page with a link for customer creation. I will make the ajax call from WelcomeController(angularJS Controller) to my servlet/spring controller
which will return html response containing js file. HTML response will be conatining below
1)HTML will be containing ng-view and ng-template which will be used by routeProvide
2)One of the js files will be containing routeProvider Info to map the ng-template with view
Please correct me if this is right approach ?
Use AngularJS for data-binding and form-validation. When you want to submit a form, you can rely on jQuery:
<div ng-controller="ctrl">
<form id="myform" name="myform">
Name: <input type="text" ng-model="person.name" name="person.name" /> <br />
<button ng-click="submit(person)">Submit</button>
</form>
</div>
Script
app.controller('ctrl', function($scope) {
$scope.submit = function(person) {
if ($scope.myform.$valid) {
$('#myform').submit();
}
}
});
For this to work, make sure you give your input fields properly scoped names so that it binds to your MVC models.
This approach does have its limitations. For example, input fields that use ngModel should not have any $formatters/$parsers which limits you to simple formats.
I was exactly looking for Single Page App with AngularJS which describes how you can have full fledged SPA web app using AngularJS(with features like router,controller,service etc) in a clear and succinct way

send HTML from servlet to JSP dynamically

Is there an easy way to send HTML from a servlet to a JSP, using AJAX.
I've already figured out how to make AJAX work with servlets dynamically, but now I want to press a button on a form and generate HTML based on text-input.
Is it possible, and if so, how, to send just pieces of HTML to an existing HTML page?
Example,
I have a basic form where you can input your age, and based on the age the text has a different size/color. So, you send for example, 25 as your age to the servlet, and it send back a piece of HTML like this <p STYLE="font-size: age;"> to the page.
Through ajax call you can get the output result either a string, html or a Json object that will be parsed and results can be displayed over JSP/HTML. So for sure you can send html code segment from servlet to jsp through ajax call.
For example you can use this approach--
1. Take a string variable in your servlet.
2. Put appropriate html string as per your conditions in this string variable
3. send this string as a response from servlet like:
response.setCharacterEncoding("UTF-8");
response.getWriter().write("your string variable here");
4. In your ajax call do like this:
success : function(dataString) {
document.getElementById("containerId").innerHTML=dataString;
},
where containerId is the id of html element (like div or span) where you want to display output html.
The easiest approach, without client-side javascript libraries, would be to point an HTML form to an iframe, just like
<iframe name="myIframe"...>
<form target="myIframe"...>
And submit your form as many times as necessary. The HTML returned by the servlet would load itself in the iframe element.
If you like AJAX and client-side javascript libraries, you can find very easy programmatical ways to do this in jQuery and similar libraries.
Basically your servlet can generate any kind of content, e.g. JSON, HTML etc.
You'd then send that content back to the client and integrate it into the page.
How that is done depends on the type of content.
Example:
You issue an AJX request (e.g. by using jQuery's ajax functionality) and your servlet generates plain html. When your JavaScript receives the anser you just replace the relevant part, e.g. by replacing the content of some defined element.
If you used JSON instead, your servlet might send data only instead, e.g. a font size based on the age as in your example. You'd then use JavaScript to access that JSON data and perform relevant operations, e.g. by changing the style of the paragraph.

how could I submit a multipart form using slim3 MVC framework?

How could I submit a multipart form using slim3 MVC framework for Google app Engine?
Example:
form.jsp:
<form enctype="multipart/form-data">
<input type=file name='filename'/>
<input type='text' name='title'/>
</form>
controller/action:
request.getParameter("title");
not working. It works only if enctype is not multipart.
What can I do?
I have tried to use
MultipartRequest req = new MultipartRequest(request, ".");
It just crashes.
When you use enctype="multipart/form-data", you obtain null values when you try to get data using getParameter, I don't remember the especific reason, but it works that way, so this is not a problem with your implementation.
One solution, using slim3, is to use getAttribute instead of getParameter. In this case, if you need to get more than one value associated whit one of your inputs, for example, if you are submitting a form and you have a group of checkboxes, you can add the word Array at the end of the name of the checkboxes in your form; this way, when you get the attribute, slim3 converts it automaticcally into an array of Strings.
You can check this information in the slim3 documentation.
I hope this helps,
Farewell.

java - how to get data of a file from a form?

I've created a form and I need the user to enter some info then upload a picture.
So lets say I have something like this:
<form method="post" enctype="multipart/form-data" action="some servlet/filter">
<input type="file" name="logo">
</form>
I need to use java to change that data to a byte[] then to blob so I can insert to a table.
How do I get the data from this form?
A bit of info on this:
I created the page using javascript, then when submitted it will call a java function to handle the data from the form. It seems that when I submit the form the data for the file is not passed over to the servlet.
So far the few methods I've tried have returned null and I'm outta ideas...
Any examples/help is greatly appreciated!
I think the main question I have is where is the file data stored before the java file start working on it? Is a special global variable holding the data or something like that?
You can use the Apache Commons FileUpload library.
The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.
If I understood you right, you need something similar to this example:
http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
I used the following tutorial one year ago:
http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html
It looks like it's a lot, but it's actually easy to understand, and it has a lot of good information.

How to access a Java object in JavaScript from JSP [duplicate]

This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 5 years ago.
I have a dropdown box in JSP, listing a Java object (accessing the object through the MVC controller's addAttribute). Now, on selection of an option from the dropdown box, I would like to display the selected employee's other details (example - ${employee.employeeCV}, ${employee.employeeName}) in a div. I have a JavaScript function for that (displayCV()). But I am not sure how to do this.
JSP -
<c:forEach items="${employees}" var="employee">
<option value="${employee.id}" onclick="displayCV();">
${employee.employeeName}
</option>
</c:forEach>
<b>CV:</b>
JavaScript
function displayCV() {
var valueSelected = $('#employeeList').val();
var div = $('#candidateDiv');
}
How can I do this?
You can't access Java classes directly from JavaScript. You have to use some kind of web service communication between the JavaScript (client) and Java (server). You can make use of the onchange event which will send a request to the server to return XML/JSON which you can parse to get the data (I see you're using jQuery, and it has parseJSON method already) and update the corresponding node in the DOM.
Another easier way, though, that is not multi-user friendly (because it can't detect updates) is to "convert" the Java object to JavaScript and update the data using that object (still using onchange). Something like:
// This is JavaScript code written in the JSP
var employees = {
<c:forEach items="${employees}" var="employee">
"${employee.id}": {
name:"${employee.employeeName}",
cv:"${employee.employeeCV}",
},
</c:forEach>
}
Now when JSP parses this, it would generate, for instance:
var employees = {
"1": {
name:"foo",
cv:"cv1",
},
"2": {
name:"bar",
cv:"cv2",
},
}
Meta of what LeleDumbo said here already:
First, you must understand that JSP is a server-side view technology, whereas JavaScript typically runs on the client (browser).
Now, how you solve the problem in hand. So, you can make an Ajax request from your JavaScript code, which will fetch you the data in JSON/XML format. Then, you can present that data in the browser using JavaScript.
Further reading: jQuery Ajax API and code samnple snippets
Call the function on the onchange event of select instead of onclick of options. And use:
document.getElementById('GrdDamagedstock_tplRowEdit_ctl00_cmbFromBin').options[ele.options.selectedIndex].innerHTML;
to get the selected value.

Categories

Resources