UPLOAD PRODUCT IMAGE
One of the most useful features in a project is server-side storage of files. In our case we will make sure to send product images, images in png format, to the server. The affected jsp page will be the item detail page. As you may recall, we have so far prepared a placeholder image, we will now give the user the option, when creating an item, to also add an image of the product displayed in the item detail. Our goal is to make sure that when an image exists that is consistent with the product code instead of the placeholder image we will see the new image. I report the changes to be made on the articolo detail page.
IsFileOk is a boolean variable that when valued at true indicates the presence of a product image having the extension .png to be displayed. It is important to note that the name of the image must be the same as the product code. Conversely, if false the placeholder image will be displayed. This boolean variable as we will see will be passed to the jsp page from the controller. Let’s create a new folder within images and call it Articoli. This is the code to put in the controller.
As you see in the parameters, the HttpServletRequest was inserted to retrieve the root directory, then a boolean variable IsFileOk was initialized to false. If the item exists, later we will see how to create that custom exception, we retrieve it and in a try catch block we go to retrieve the path to the image. We then create a new file having as its path the path to the image if it exists and value the boolean variable with the exists() method of the File class, which returns true if the file exists, false otherwise. Finally, we pass the boolean variable to the view via the model.
NB: Beware of the PathImages which on macOS is as follows:
private final String PathImages = “static/images/Articoli/”
On Windows and Linux, the bar symbol dividing the path may differ. Go to debug if you don’t see the image.
SEND A FILE TO THE WEB SERVER
We will now give the user the ability to insert an image file from the article entry view. The first step is to add a new dependency to the pom.xml file.
To enable the upload of any type of file to the server we need to create a new configuration class, MultipartResolverConfig.java. As a first step when we are dealing with a configuration class we need to add the notation @Configuration, this will tell the IOC to load that class when the application starts.
I created a new Bean in which I specified all the previously defined constants, then within a try catch block I determined the upload temp directory and physically performed the upload to the server, finally I returned the resolver. This Bean will allow us to do the file transfer to the temporary directory. Then from the temporary directory the files will need to be written to the primary directory the one where the files will actually need to be placed, i.e. the Articoli folder under images. This will be the work that another part of our application will do. Now let’s make a change to the domain class where I added the private field private MultipartFile Immagine; and the respective getters and setters. Technically this is the variable that will contain our image. Now let’s go edit the controller in the new item insertion method.
CHANGES MADE TO THE CONTROLLER
I inserted a new variable of type MultipartFile that I get from the getImmagine() property of the domain class. The code should be entered after checking for validation errors, the first two lines are used to get the path to the image if present the third line within the try is the most important and is used to do the file transfer from the temporary directory to our Articoli folder. Last change to the controller is to initializeBinder where we need to add “image”.
enctype=“multipart/form-data” added at the form level indicates that this form can perform file transfers. To test how it works use the image you have available within images/Articles move it to a new location and create a new product having the same code as the image, I named it C000001 do the upload so that you transfer the image to the temporary directory and when you save the image it will move from the temporary folder to the Articles directory. Once you have made the entry go to the item detail, you should see the image of Findus sofficini.
EXCEPTION HANDLING
Try opening an item detail, in the url type a nonexistent product code. What you get is an internal server error screen http status 500. It’s certainly not a pretty screen to look at or professional. We will now make sure to create a custom exception that informs the user that the typed product code does not exist. We create a new package
com.xantrix.webapp.exception and add the class NoInfoArtFoundException.java.
As you can see, the class extends the RuntimeException. It is a very simple class that needs no explanation, the only thing is the @ResponseStatus notation whose value specifies that where you will enter a page with an item not found then this class will intervene. Let’s go into the controller and create a new method.
It will be exactly this method that will handle our error, to do this we have to insert a specific notation @ExceptionHandler that takes as argument the class we just created. The ModelAndView is a variant of the Model we have used so far, as you see it is quite similar, you set the values to pass to the view with addObject, set the view with setViewName and finally return the object. The exception is handled in the item detail, if the recordset found is null or empty we throw the exception. Now we need to create the new noInfoArt view, so we edit the tiles.xml and create the new view whose code I reproduce.
RETURN DATA IN JSON OR XML FORMAT
Up to this point in the discussion we have always returned data in html format. We are not constrained only to this format; in fact, we can return the response in JSON or XML format as well. JSON format is the most widely used format for data interchange, the somewhat older XML format is still used as an interchange format but in Web Services. The first step is to add new dependencies to the POM.XML file
The next step is to edit our main configuration file, we proceed to insert two new Beans that will take care of the conversion to the desired formats.
In the setClassesToBeBound method we specified only the class Articoli for the time being. The next step will be to specify the ViewResolver, as we will remember is the ViewResolver that transforms the model data into the format that we want, the most important part of this code is when in the ArrayList class we go to add the two Bean just created. Modified the configuration class we make a small change to the class Articles, at the top of the class we use the notation @XmlRootElement which specifies the root for XML conversion. In the private MultiPartFile Image field, we use the notation @JsonIgnore as this field is not to be displayed. The last notation to insert is in the image getter and is the @XmlTransient. Once you have made these changes go to an item detail and display the data either in JSON or XML format.
DOWNLOAD ARTICLE CODE
The AlphaShopV4.zip project is for the SQL Server DBMS while AlphaShopV5.zip is for MySQL.
Leave A Comment