JSP Download Csv File - java

I'm working on the problem for almost one day,and I can't figure out a solution.
I want to add a download service into my jsp page,and the code like this:
response.setHeader("Content-Disposition","attachment;filename=authData"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+".csv");
PrintWriter out = response.getWriter();
and I use a trigger button to link to background.and the codes like this:
<input type="submit" class="btn_sure fw" value="query" onclick="queryAuthDataList();"/>
<input type="reset" class="btn_cancel fw" value="reset">
<input type="submit" class="btn_sure fw" value="download CSV" onclick="exportAuthDataList();" >
and the following onclick funtion like this:
function exportAuthDataList(){
$("#queryAuthDataForm").attr("action","export").submit();
}
function queryAuthDataList(){
$("#queryAuthDataForm").attr("action","query").submit();
}
for some reasons , I must use GET to collect the tag names and values in jsp file.
Here comes the problem,when I select data from DB2,and there're many results,I must paging them,But when I click next page,it's starting download csv file automaticly.I define different redirect keywords in Jquery,but I can't simplely add jquery function in the "next page" link.Because I may get some other links.
How can I stop the file downloading when I click a different link ?

Related

How to submit another get attribute and keep previous one?

I'm building my first web app in Java. I came across this problem. When I have a get attribute like ?page=2 correctly submitted it goes missing after calling another get request. How can I keep the first one and append another one? Here are pics that help clear out my question
Before
After
Desired
Here are code snippets of my forms in .jsp page. This is used to sort the table with passing a column name:
<form action="GetUsersServlet" method="get">name
<input type="hidden" name="column" value="name">
<button class="sort" type="submit"></button>
</form>
How can I append the value to existing ?page=x attribute?
Use URLSearchParams method set on event click and set window.location.search to parsed params.
document.querySelector("button").onclick = () => {
const urlParams = new URLSearchParams(window.location.search);
urlParams.set("page", 2)
window.location.search = urlParams.toString()
}

Spring MVC - How to pass data from jsp page's button to Controller?

I have a line of code like this in the jsp:
<button name="CurrentDelete" value="${ra_split}" type="submit">Delete</button>
And in my Controller I use:
#RequestParam String CurrentDelete
I am trying to pass the value of ${ra_split} into the Controller when I hit the Delete button, but all I am getting is the value of the text 'Delete' instead. Why is that?
Here's the explanation
If you use the element in an HTML form, Internet Explorer, prior version 8, will submit the text between the and tags, while the other browsers will submit the content of the value attribute.
By returning to this issue after a few days I figured out a solution.
Just use:
<input type="hidden" value="${ra_split}" name="CurrentDelete">
<input type="submit" value="Delete" />
instead of:
<button name="CurrentDelete" value="${ra_split}" type="submit">Delete</button>
Then the problem will be solved and the String CurrentDelete will contain the value ${ra_split} instead of the text 'Delete'.
Extra information I have got when trying to solve the problem:
The button tag:
<button name="CurrentDelete" value="${ra_split}" type="submit">Delete</button>
Will always pass the value between the button tags to the Controller (in this case the text 'Delete') instead of passing the value="${ra_split}".
Either using
HttpServletRequest req
in the Controller and then do:
String CurrentDelete = req.getParameter("CurrentDelete");
or using
#RequestParam String CurrentDelete
in the Controller,
would both get the same result.

Angularjs UI Bootstrap Popover Prevents input submit

I have used Angularjs with ui.bootstrap popover feature in following manner,
<form name="frm1" role="form" ng-submit='myFunc()' novalidate="novalidate">
.... other inputs go here...
<input type="number" ng-pattern="/^[0-9]+$/" name="testNo" ng-model='testNo' required popover="Locate number here" popover-trigger="focus">
<input type="submit" ng-model='funcBtn' value="Submit" ng-click="submitted = true" ng-disabled="value.length=0">
</form>
The issue is because of popover="Locate number here" popover-trigger="focus" code when I check after submitting the form the value for the input testNo is not passed to controller.
The Controller is as follows,
app.controller('myCtrl', ['$scope','$location','$log', function($scope,$location,$log)
{
$log.log('testNo', $scope.testNo);
}]);
And If I remove the popover code from this input it works fine. I like to know whether there's a specific way in using popover into inputs.
Used resource ui.bootstrap example, input trigger: http://angular-ui.github.io/bootstrap/
The problem is that the current version of AngularJS can only have one scope for a given DOM element, and the popover creates a child scope that then gets inherited by the other directives. Fortunately, the solution is simple. Just refer to $parent.my_var in the directive, in your case ng-model="$parent.$model".
Here is the popover FAQ on this problem.
I ran into this problem in the bowels of my own custom directive, but fortunately the solution is simple there as well: rather than refer to $scope.var, refer to $scope.parent.var. Simple solution, but hours of debugging!

Trying to use a #RequestParam field in Spring form [duplicate]

Consider this form:
<form action="http://www.blabla.com?a=1&b=2" method="GET">
<input type="hidden" name="c" value="3" />
</form>
When submitting this GET form, the parameters a and b are disappearing.
Is there a reason for that?
Is there a way of avoiding this behaviour?
Isn't that what hidden parameters are for to start with...?
<form action="http://www.example.com" method="GET">
<input type="hidden" name="a" value="1" />
<input type="hidden" name="b" value="2" />
<input type="hidden" name="c" value="3" />
<input type="submit" />
</form>
I wouldn't count on any browser retaining any existing query string in the action URL.
As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:
If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.
Maybe one could percent-encode the action-URL to embed the question mark and the parameters, and then cross one's fingers to hope all browsers would leave that URL as it (and validate that the server understands it too). But I'd never rely on that.
By the way: it's not different for non-hidden form fields. For POST the action URL could hold a query string though.
In HTML5, this is per-spec behaviour.
See Association of controls and forms - Form submission algorithm.
Look at "4.10.22.3 Form submission algorithm", step 17. In the case of a GET form to an http/s URI with a query string:
Let destination be a new URL that is equal to the action except that
its <query> component is replaced by query (adding a U+003F QUESTION
MARK character (?) if appropriate).
So, your browser will trash the existing "?..." part of your URI and replace it with a new one based on your form.
In HTML 4.01, the spec produces invalid URIs - most browsers didn't actually do this though...
See Forms - Processing form data, step four - the URI will have a ? appended, even if it already contains one.
What you can do is using a simple foreach on the table containing the GET information. For example in PHP :
foreach ($_GET as $key => $value) {
$key = htmlspecialchars($key);
$value = htmlspecialchars($value);
echo "<input type='hidden' name='$key' value='$value'/>";
}
As the GET values are coming from the user, we should escape them before printing on screen.
You should include the two items (a and b) as hidden input elements as well as C.
I had a very similar problem where for the form action, I had something like:
<form action="http://www.example.com/?q=content/something" method="GET">
<input type="submit" value="Go away..." />
</form>
The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).
If you need workaround, as this form can be placed in 3rd party systems, you can use Apache mod_rewrite like this:
RewriteRule ^dummy.link$ index.php?a=1&b=2 [QSA,L]
then your new form will look like this:
<form ... action="http:/www.blabla.com/dummy.link" method="GET">
<input type="hidden" name="c" value="3" />
</form>
and Apache will append 3rd parameter to query
When the original query has array, for php:
foreach (explode("\n", http_build_query($query, '', "\n")) as $keyValue) {
[$key, $value] = explode('=', $keyValue, 2);
$key = htmlspecialchars(urldecode($key), ENT_COMPAT | ENT_HTML5);
$value = htmlspecialchars(urldecode($value), ENT_COMPAT | ENT_HTML5);
echo '<input type="hidden" name="' . $key . '" value="' . $value . '"' . "/>\n";
}
To answer your first question yes the browser does that and the reason is
that the browser does not care about existing parameters in the action URL
so it removes them completely
and to prevent this from happening use this JavaScript function that I wrote
using jQuery in:
function addQueryStringAsHidden(form){
if (form.attr("action") === undefined){
throw "form does not have action attribute"
}
let url = form.attr("action");
if (url.includes("?") === false) return false;
let index = url.indexOf("?");
let action = url.slice(0, index)
let params = url.slice(index);
url = new URLSearchParams(params);
for (param of url.keys()){
let paramValue = url.get(param);
let attrObject = {"type":"hidden", "name":param, "value":paramValue};
let hidden = $("<input>").attr(attrObject);
form.append(hidden);
}
form.attr("action", action)
}
My observation
when method is GET and form is submitted, hidden input element was sent as query parmater. Old params in action url were wiped out. So basically in this case, form data is replacing query string in action url
When method is POST, and form is submitted, Query parameters in action url were intact (req.query) and input element data was sent as form data (req.body)
So short story long, if you want to pass query params as well as form data, use method attribute as "POST"
This is in response to the above post by Efx:
If the URL already contains the var you want to change, then it is added yet again as a hidden field.
Here is a modification of that code as to prevent duplicating vars in the URL:
foreach ($_GET as $key => $value) {
if ($key != "my_key") {
echo("<input type='hidden' name='$key' value='$value'/>");
}
}
Your construction is illegal. You cannot include parameters in the action value of a form. What happens if you try this is going to depend on quirks of the browser. I wouldn't be surprised if it worked with one browser and not another. Even if it appeared to work, I would not rely on it, because the next version of the browser might change the behavior.
"But lets say I have parameters in query string and in hidden inputs, what can I do?" What you can do is fix the error. Not to be snide, but this is a little like asking, "But lets say my URL uses percent signs instead of slashes, what can I do?" The only possible answer is, you can fix the URL.
I usually write something like this:
foreach($_GET as $key=>$content){
echo "<input type='hidden' name='$key' value='$content'/>";
}
This is working, but don't forget to sanitize your inputs against XSS attacks!
<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" />
</form>
change the request method to' POST' instead of 'GET'.

Pass a file to Java trough JavaScript

I have been trying to load a file trough a form in HTML and send it to Java in order to process it. I made a JavaScript function so i can pass the file path but it won't work because it will send only the file's name and extension so Java will just get just a String to process and throw a NullPointerEception.
Does anyone have any idea how i can solve this problem?
PS: I'm sorry for the noobie question but i don't know JS.
i think the file which you forward for java is must read by input output operation in bytes beacuse java is understand only text file or byte array by byte array you can store any image ,pdf etc.
i have a regular html form like this:
<form action="MultipartServlet" name="form" id="form" method="post" enctype="multipart/form-data">
<td><input type="file" name="upload" id="upload" />
<td><input type="button" value="Check" onclick="FileValidator.check()"/>
i cannot use type="submit" because for an odd reason the application is crushing
the JS code:
check: function() {
var file = $F("upload");
new Ajax.Request( 'url', {
parameters: '...&action=fileValidator&upload=' + file,
onSuccess: function(response) {
var result = eval('(' + response.responseText + ')');
if (result.success) {
displayErrorsFromFile();
} else {
alert("Errors! " + response.responseText);
}
},
onFailure: reportError
})
}
in the Java code i just try to get the file trough the "upload" parameter and validate the file's imput.
so i guess that the "upload" parameter has to get a bites array of the entire file so it can process it... or somehow the path of the file
"The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data."
http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
What does enctype='multipart/form-data' mean?
So basically it doesn't really matter how your submit your form on the client, <input type="submit" />, some java script like document.forms["myform"].submit(); or however your js library does it, as long as you have <input type="file" /> in your form on the client and some server side component (like servlet), which could get to the binary file submitted, from the request.
For e really comprehensive example and explanation see this post:
How to upload files to server using JSP/Servlet?

Categories