I wrote a small log-in java program that works with servlets, and JSPs using the MVC pattern that allows me to register and log-in accounts(if we can call them that) to my local mySQL DataBase. I am using sessions to pass values between the servlet and the JSP, and I have a list of if statements on the servlet that work as validation for invalid inputs. Right now when my application is executed this happens:
Sign_Up.jsp opens up and displays UserName and Password fields with a submit button below it. Also it shows a link on the top left corner to the Log_In.jsp. If you enter an username and password that follows requirements, an account is created on the database, and you are redirected to the Welcome.JSP which only shows a few lines of text. (I am not checking weather the password and username entered are unique atm, so there are duplication entries in the user table on the DB)
If you click on the link at the top of the Sign_UP.jsp, then you are redirected to the Log_In.jsp. Here you are required to enter your credentials, if they exist on the database you are redirected to the Welcome.jsp , otherwise you are told that they are invalid and that you need to enter them again.
-----------------------------------THIS IS WHAT I WOULD LIKE TO DO NOW--------------------------------------
Once an account is validated and redirected to the Welcome.jsp I would like that page to show a button that says "Choose File", which when clicked will allow you to browse your computer for files. From there I should be able to select a .csv file that I can parse and enter into the database. Maybe the .csv will contain something as simple as:
Username , Password
UserTest1, 123
UserTest2, 234
UserTest3, 567
UserTest4, 890
So these are my questions regarding this whole procedure:
Is it possible to use JS inside a JSP to accomplish my task?
Is it a good idea to use JS inside a JSP to do it?
If I were to built a more complex website is it recommended to build it using html,css and jQuery code inside the JSP?
The whole idea is to build a a website that allows the admin ONLY to enter a .csv file containing a list of prices for items, that will be grabbed by the website and uploaded into the database, which in return will show a new stock of items for a certain product. I know that I am far from done, but this is just a start. :)
You don't need JavaScript to upload a file
I don't see how it would help. Just use a input of type file
You can of course use JavaScript, whatever you use at server-side to generate the HTML pages. Embedding JavaScript code inside HTML pages is a bad practice though. You should try to externalize the JS code to .js files as much as possible.
Just a few notes regarding the title and body of your question:
reading a CSV file is the job of the controller, not the job of the view
using the session to pass objects from a servlet controller to a view is not what you should do. You should use the request to do that.
You can't read files with JS because it doesn't have permission to access the filesystem.
You will have to upload the file into the server and get the parsing done from there.
There are tons of examples for JSP file uploading in the net.
Most complex websites employ the technologies/libraries you have listed so the answer is yes use them and it will increase usability and look and feel.
Related
I have a problem about using Struts to download a file. I know Struts is an old technology, but my company is maintaining an old application for a customer.
So, problem is that we want a webpage to download a file. Scheme is the following : Reach for webpage > click a button > execute treatment (DB query and data selection) > produce excel file > download the file > back to initial page.
My code is working until the file download, i.e. I can download a correct excel file, but I can't go back to the original webpage.
I read this answer and others in this forum, and it seems that downloading a file and going back to original page are 2 different treatments, and that Struts can only process one...
I absolutely need those 2 treatments, so my idea is the following : When the user clicks the button on the original page, I should open another window (or even a pop-up) which will take care of the excel treatment and download, and my original page won't move, therefore I don't need to forward at the end of the treatment.
Question is, do you think this is viable ? I couldn't find a similar code here so I guess it isn't a good idea, so if you have a good practice about my need, please share it :)
Yes sure your idea will work. But the user has to close the pop-up after the download starts.
Just to give some other ideas:
I had a similar problem once and solved it a little bit different. Javascript does allow execution of multiple statements in one row with one button (what you would do anyway with the popup and redirect solution).
So you could listen on the click event on the button and download the file and do something different after that.
Here are some topics about downloading files with javascript Link without using a popup. And a simple javascript redirect is also very easy Link #2.
The glue code to struts are two links you have the generate while the user visits your page.
More or less pseudo-code in html/jquery:
<button id="download" data-downloadlink="<s:property value='downloadlink'/>" data-redirectpage="<s:property value='redirectpage'/>">Download</button>
$('#downloadbutton').on('click', function() {
download($('#downloadbutton').data('downloadlink'));
redirect($('#downloadbutton').data('redirectpage'));
});
Is there a way to display a (preferably modal) dialog box in an servlet controller ? If it isn't modal that is something I can deal with (!?) as long as it initially appears above the browser.
Essentially I have a form with a table and 2 buttons on it. One button takes the user to a different place in the workflow and is irrelevant to this question (just to explain why the other one doesn't 'go anywhere').
The other button currently goes back to an MVC controller, calls some code to export the table to excel and then reloads the web page. This is all working okay except the way I am calling the dialog box is calling it underneath the browser. I suspect this is because I am sending null as the frame but I'm not sure what to put in its place ?
JOptionPane.showMessageDialog(null, "Export Completed.", "Excel Export", JOptionPane.INFORMATION_MESSAGE);
Many thanks.
I am not too sure what you are trying to achieve from your question and without any code examples. However, presumably what you are doing (guessing here), is that you are trying to export some data from some data source and convert it to an Excel file. You have to keep 3 things in mind.
Web applications work via HTTP requests and responses. So the only thing a Servlet can do is send back an HTTP response that indicates that the export was successful. Whether you use a traditional page, or maybe use AJAX to avoid refreshing the page is purely your design choice. You could also start with a simple page and then change to AJAX combined with JQuery later once you get used to what is happening.
Exporting the excel sheet to the server does not mean that your client has access to it. Speculating here, but you will probably need a mechanism for your user to get the file. One simple approach used by many webapps is to actually send the Excel file as the Servlet response itself. So what would happen is that when the export is completed the browser starts receiving the file and the user sees it downloading. From your servlet you will just need to set the right mime-type and set the content-disposition header to state that the file is an attachment (so that the browser downloads it as a file).
httpresp.setContentType("text/csv");
httpresp.setHeader("Content-disposition", "attachment; filename=\"export.csv\"");
You will probably also need to set the file size. There are various full examples on SO if you look for further details.
When performing these operations remember that users can interrupt the browser or refresh. If the user presses F5 he might cause your application to do the export again. One common approach to this is called 'redirect-after-post'. Basically you redirect the user to a page which just displays the outcome, without performing the operation again. This way if he presses refresh, he is just refreshing the page with the message.
I have a image placed in a jsp. I have the image kid.jpg downloaded and kept in /resources/images folder. The below is the code snippet.
<li style="background-image: url('resources/images/kid.jpg');">
Now my web app is up and running. How to give end user to change that image/ upload a different image in that place. The same with the text in a div.
I am not getting the data from database and adding to the div dynamically.
Is database communication only way in such cases or any other way? I see many web sites contents are changing day by day. Are they modifying the webpages and replacing the existing files/ are they getting the data from database?
Please suggest how to achieve such scenarios.
Thanks
If There is no database on server and you want to allow all users ( unregistered ) to change a specific image, then what you can do is :- store the image file name in cookie, and on server check every time for that cookie, and if does not exists and render the same output with default image, other wise use that cookie's file_name image , and then on client side you can provide a facality to users to select images from particulers images that reside on server, and when user select some image so save that file name in cookie :) , Sorry for spelling mistakes, It's just a overview of solution of your problem :)
I like playing Magic: The Gathering, and I also have a database of my collection. Magic set information was easy to obtain, since I could parse it directly from the HTML URL stream I opened, but I'm now trying to obtain prices for the cards as well from Star City Games (a MTG vendor). However, when I view source, there are no prices in the HTML; it's all done through JavaScript on-the-fly. Here's an example page for reference: http://sales.starcitygames.com/search.php?substring=Snapcaster+Mage&t_all=All&start_date=2010-01-29&end_date=2012-04-22&order_1=finish&limit=25&action=Show%2BDecks&card_qty%5B1%5D=1&auto=Y
The webpage generates the following HTML: http://pastebin.com/Psrpri8r .
I just want to be able to read the text "24.99." All of the code I'm using is in Java.
Thanks.
You need to run javascript... Try selenium.
If you dont want to learn him, i've an Hacky solution (Warning: very complicated): Download the page to your computer (Download also all the .JS pages), Edit the JS code that send the relevant data to your server instead showing it, And open this page in browser.
It is quite a common question but I can't find an answer to it
I have a simple HTML with an input text box (type=file) and a submit button. On clicking the submit button, I call a js function where I try to get the complete path of the file
var data = $('#fileName').val();
the issue is I am not getting complete file path of the file I am uploading. I know due to security reasons chrome gives me a C:\fakePath\filename and firefox gives me only the fileName. But in case I need a complete path what shall I do?
PS: Further I will make an ajax call and give that file path to the back-end which needs it to read that file using FileReader
You cannot get the complete path! there is no way to do that!! Even though you are on an intranet and you have enough permissions.
A workaround for this is to have a textarea and ask the user to enter the complete path of the file.
In short you can't have the full name of a file once is loaded on server side, you will just have the file name and its content in a raw byte array (among other attributes). This is not a Java thing nor other server side technologies issue, is related to browser implementation (but it looks that IE6 may contain a flaw about this).
Not directly related to your question but caught my attention
PS: Further I will make an ajax call and give that file path to the back-end which needs it to read that file using FileReader
Usually, you can't handle a file upload using ajax because it can lead to security holes. Still, there are some browsers (like Chrome and Firefox) that allows you to send a file using XMLHttpRequest but that isn't allowed on some browsers (like IE8-) so you have to use an iframe in order to make the file ajax uploading work.
In order to avoid handling all these problems, I would advice you to use a third-party js library that handles the ajax file upload. An example is blueimp jQuery file upload that also has Java server side examples (DISCLAIMER: I do not work in this project nor I'm associated with blueimp in any way). Note that using this plugin requires that you have a mid knowledge on HTML/JavaScript/jQuery/Java Server Side so if you're a starter it may take you some time to make it work, but once it does is pretty good.
I dont know which technology you are using.. but you can always get file name once it is uploaded on server (Using php or .net )
your steps to upload should be like below:
1) Upload file to the server (e.z. /uploadedFiles/...filename
2) Create a method which will fetch file name from the uploaded path
3) simply insert file name in to the database (this will give you flexibility to change folder name of uploaded docs in future if required)
Generally filenames are not stored as it is . to avoid name conflict in future. So it is a advisable to always rename your filename by adding minutes & seconds after itsname.
If any doubts do ask.
Hope it helps.
Browsers block the filepath access on javascript for securit reasons.
The behavior makes sense, because the server doesn't have to know where the user stores the file on his computer, it is irrelevant to the upload process.