Making a Spring MVC MP3 Media Info Site


After the basic setup covered in the first part of this document where moving on to the reason I made this tutorial.

Download and open the “starting code” file, it works but I left a couple unneeded codes in it so we can cover them, the first is:

${example}

this code is still in the upload file, so open it and remove it, if you remember this is used to change the header text on the page in the controller file so lets remove it and add a header of your choosing.

After doing this go to the controller file and find mv.addObject("example", "test");

if you remember this is what sets the header text to what ever you want, so removing this after removing ${example} prevents the system from having redundant functions.

So lets start.


Uploading


This application first gets an MP3 file and reads its meta data then shows it to the user. Before we can do that we need to upload a track. This is easy but would need a library file called commons file upload and commons IO download and add that to the library Here.

What this does is tell spring how to handle uploads remember to add any corresponding Java doc files for referencing.

Then in the dispatcher add the this bean:

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

what this does is add the commons MultipartResolver to your application.


So now run your code and see what you have so far:




Basic I know but we almost have everything we need, it doesn't need to be pretty yet.

Next open the upload file and look at the form data, this is incomplete these two lines need changing.

<form method="post" enctype="multipart/form-data">


<input type="submit" name="submit" value="Upload">${message}

In the first line we need to add a action to the form action=”Uploaded.htm” and in the second line we need to remove ${message} because we will not be using it this go round.

Now where ready to move on, lets open the uploaded jsp file. Lets change the title and the header to ${mytrack} this will be the name of the track where looking at.

If you run this ad go to the page you will get an error message thats because we havent added it to the mapping yet so open the dispatcher file (MusicChecker-servlet) and add the bean:


<bean name="UploadedController"

class="Controller.UploadedController"

/>

Then in the urlMapping add this in the props:


<prop key="Uploaded.htm">UploadedController</prop>

Now all we need is a controller for this so in the Controller package add a java class and name it 
UploadedController. Almost done now add implements Controller to that class:




press the light bolb and select “import org.springframework.web.servlet.mvc.Controller;”

press it again and select implement all abstract methods.

Now we have mapping a page and a controller but theirs an error message although a different one.




If you read it it just says this is not yet supported. That’s because by default netbeans makes this error when you auto fill a controller. So lets go back to the controller.




Okay lets remove the exception thrown in this. Right now we don't need this to do anything but we do need to return a model and view or we would get an error so simply declare a new model and view and return it using mv as the variable name.

After doing this you will get a blank page that means that all is good. Anything you do in the JSP file will now show up on that page.


Back to the functionalities, lets test that files are being uploaded, in the uploaded jsp file add ${test} anywhere that can be seen then in its controller add;


mv.addObject("test",hsr.getContentType());


after the mv initiation.


What this does is find the file type and sends it to the web page. Now run the page and upload a file no matter the file type just add it for testing. If it works you should get something like “multipart/form-data;”.




Now explanation in spring when you upload a file it would be sent as a HttpServletRequest in an argument, Netbeans automatically calls this variable hsr.


So when ever we use hsr where referring to information received from the previous page or action.


Now lets add music functions, we first need to validate that what we have is an mp3 file. So lets first remove all the testing things we just added and replace them in the controller with:


if (!(hsr instanceof MultipartHttpServletRequest)) {

mv.addObject(“status”, “no file uploaded”)

return mv;

}

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) hsr;

MultipartFile file = multipartRequest.getFile("file");




what this does is check to see if there are uploaded files if not it will return an error message by now you should know how to show the message by looking at the code.




Then the next thing it does is add the file to a file object in this case a MultipartFile as that’s the file type used to transfer the data.



So now we have a file but we don't know what it is.




Now what we need is a file object, the multi-part file object is useful but hard to use for what we want so what where going to do is convert it to a file object. As you should know a file object in Java is really just a object holding a string saying where the file is on the system, so converting the physical file to a reference to where the file is would be pointless mainly since the multi-part file is literally in multiple parts. So what we need to go is join the parts and save it to a place that can then be referenced.




The first thing we need is a file object so add this line:




File myfile = new File(System.getProperty("user.dir")+"/temp/"+ file.getOriginalFilename());




what this does if you read it is make a file object and position it in the temp folder:





System.getProperty("user.dir"): this part tells the system in needs to use the current directory this prevents the system from using the root directory and allows a better control of where your files are kept.




file.getOriginalFilename(): this just gets the name of the file you uploaded as it was when you uploaded it preventing any wrong names or conflicts.





And as you can see where saving it in a folder called temp.


just pointing out that this hasn't saved the file just made a object saying where the file is, if you test it with the isfile() method you will get a no.

so wat we need now is to actually save the file where the file object thinks it is. To do that multi-part file has a built in method called transferto():

if(!myfile.exists()) {

myfile.mkdirs();

}else{

uploading.addObject("mytrack","File already being working on");

return uploading;

}

file.transferTo(myfile);




before using this method its a good idea to test if the file already exists, and making any directories that might be needed. What the transferto() method does is save the file in the file path of the file object. (not meaning to use so many file references)

so now we have a file object with a file linked to it so if we run the isfile() method again we will get a yes this time.


All good so far test it and see if it saves and you can get a yes you can also get the path on your system to test if the file was saved correctly.


This should look like this:

But if you run it again you will get this:


This is because the file was actually saved on the system in the folder above and i added this error message if your uploading the same file and over writing it:




so when where done using the file we will go over removing it as to prevent replication or over crowding when we actually put it online.

As you can see I used an image instead of a MP3 in the test what we want is to add a function that will test to see if a file is a MP3 or not.


To do that what I did was make a new class for music for you, so add a new package called music and add the classes in the download Here files and then add the jaudioTagger library. After doing that change the file test to this:



What this does as you can see is just tests if its a mp3 track with valid tags.

Lets get rid of the test variable and move on, now we know what we have is a valid mp3 file and it has been uploaded, so lets get the information we need.

To do so I made a class called JSONTrack what this does is simple it creates a object that holds all of the tracks information got using the Java audio Tagger library.

To make a JSONTrack object using a file you first will need to add this line.

JSONTrack myTrack = TrackFinder.getFileTrack(myfile);

Now that you have all the information needed just add them to the model and view like this.


mv.addObject("mytrack", myTrack.getTitle());

mv.addObject("album", myTrack.getAlbum());

mv.addObject("artist", myTrack.getArtist());

mv.addObject("genre", myTrack.getGenre());

mv.addObject("time", myTrack.getDuration());


Now where done with the coding simple so far right. All we need to do now is add everything to the view i.e. the JSP file with this code here.

<table width="100%" border="1" align="center"> 

<tr><td colspan="3"> 

<h1 align="center">${mytrack}</h1> 

</td> </tr> 

<tr> <td> ${album} </td> 

<td> ${genre} </td> </tr> 

<tr> <td> ${artist}</td> 

<td> ${time} </td> 

</tr> 

</table> 

Now that that’s done all we need to do is clean up the code a bit. If you remember the code saves the file on the system and prevents the same file from being checked more than once, that's an issue because track after track every one has to be different. What where going to do now is remove the track after the JSONTrack object is made. To do that all we need to do is add:

myfile.delete();

Bit simple but it will remove the file when executed leaving the information for the user to view.



And where done :) simple.

Try it out 


No comments:

Post a Comment