Get all Request Parameters in Java

In this tutorial, we’ll show you how to get all request parameters in java. Ideally, the server should know the parameter names that was sent by the client browser. I have created a simple Spring Controller that gets a request from the client and redirect the user to another page that displays all his request parameters and its values.

Create A Servlet Controller

In our Controller, we take a parameter HttpServletRequest which contains the client request including its parameters.

@Controller
@RequestMapping("/sample")
public class SampleController {

@RequestMapping(value = "/get", method= RequestMethod.GET)
public ModelAndView getParameters(HttpServletRequest request){
    Enumeration enumeration = request.getParameterNames();
    Map<String, Object> modelMap = new HashMap<>();
    while(enumeration.hasMoreElements()){
        String parameterName = enumeration.nextElement();
        modelMap.put(parameterName, request.getParameter(parameterName));
    }
    ModelAndView modelAndView = new ModelAndView("sample");
    modelAndView.addObject("parameters", modelMap);
    return modelAndView;
}
}

To get all request parameters in java, we get all the request parameter names and store it in an Enumeration object. Our Enumeration object now contains all the parameter names of the request. We then iterate the enumeration and get the value of the request given the parameter name.

We store the the name and its value in a Map and add it to a ModelAndView and redirect to sample.jsp. Below is the sample.jsp file:

<%@ page import="java.util.Map" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Display All Request Parameters</title>
</head>
<body>
<h4>List of Request Parameter Names and its Values</h4>
    <%
        Map<String, Object> modelMap = (Map<String, Object>) request.getAttribute("parameters");
        for(String key: modelMap.keySet()){
            out.print(key);
            out.print(" : ");
            out.print(modelMap.get(key));
            out.print("<br />");
        }
    %>
</body>
</html>

Testing our WebApp

To test it, we type the url in the browser:

http://localhost:8080/sample/get?name=javapointers&language=java&version=8

When we hit Enter, the resulting page is below:

get-all-request-parameters

Java Convert Image to Base64 String and Base64 to Image

In this post, we will be converting an image to base64 string so that it can be save to a database, more accurately in a blob type column.

Encode Image to Base64 String

The below method will encode the Image to Base64 String. The result will be a String consisting of random characters, representing the image. This characters can then be save to the database. A blob type column is more applicable when saving an image to the database since a blob column can hold large amount of data.

public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

Decode Base64 String to Image

Meanwhile, you can also decode your base64 string to an image to be save or sent to the client. Below is a method on how to decode base64 string to image.

public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

For example, if the data/string came from a client request, if the base64 string starts with something like data:image/png;base64,iVBORw0KGgoAA….. you should remove data:image/png;base64, . Therefore, your base64 string should starts with eg. iVBORw0KGgoAA.

How to Crop Image in Java

Sometimes, you need to crop an image. In order to crop image in java, we will use the method subimage from BufferedImage class.

bufferedImage.getSubimage(x, y, width, height);

Example:
This static method will return the cropped image given the starting x and y coordinate and the width and height that will be cropped from the image.

/**
     * Crops an image to the specified region
     * @param bufferedImage the image that will be crop
     * @param x the upper left x coordinate that this region will start
     * @param y the upper left y coordinate that this region will start
     * @param width the width of the region that will be crop
     * @param height the height of the region that will be crop
     * @return the image that was cropped.
     */
    public static BufferedImage cropImage(BufferedImage bufferedImage, int x, int y, 
                                          int width, int height){
        BufferedImage croppedImage = bufferedImage.getSubimage(x, y, width, height);
        return croppedImage;
    }

To read an image from a file, we can do:

File imageFile = new File("C:/Javapointers/image.jpg");
BufferedImage bufferedImage = ImageIO.read(imageFile);

This method will return the image buffered from the file.

After cropping the image, we can now save or write the file to the file system using:

File pathFile = new File("C:/Javapointers/image-crop.jpg");
ImageIO.write(image,"jpg", pathFile);

where image is the cropped image.

Create Cookie Example in Java

Here is a simple cookie example that will be added to the response and to the user’s browser.

Creating a Cookie

@RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home(HttpServletResponse response) {
        //create a cookie with name 'website' and value 'javapointers'
        Cookie cookie = new Cookie("website", "javapointers");
        //set the expiration time
        //1 hour = 60 seconds x 60 minutes
        cookie.setMaxAge(60 * 60);
        //add the cookie to the  response
        response.addCookie(cookie);
        //return the jsp with the response
        return "home";
    }

Reading a Cookie

@RequestMapping(value = "/home/cookie", method = RequestMethod.GET)
    public String readCookie(HttpServletRequest request) {
        //get all cookies
        Cookie[] cookies = request.getCookies();
        //iterate each cookie
        for (Cookie cookie : cookies) {
            //display only the cookie with the name 'website'
            if (cookie.getName().equals("website")) {
                System.out.println(cookie.getValue());
            }
        }
        return "home";
    }

Checking your browser

Below, we can verify that our cookie has been successfully added to the browser.

cookie

 

How to Upload File in Spring MVC

Spring has a built in MultipartFile class that is necessary to upload file in spring mvc. In order to upload file in spring mvc, we need to configure our dispatcher-servlet.xml to add the maximum file upload size, creating a controller and a logic to save the file that was uploaded. This assumes that you have already a working spring mvc project or click here on How to Create Spring MVC Project using Maven.

1. Modify you dispatcher-servlet.xml to Upload File in Spring MVC

Create a new bean that defines that maximum upload size of the file.


         

Your dispatcher-servlet.xml should be look somthing similar to this:




    
    

    
        
            /WEB-INF/jsp/
        
        
            .jsp
        
    

    
    
         
    

    


2. Create your Upload Controller

Create a Controller class that will handle file upload in spring mvc.

package com.javapointers.controller;

import com.javapointers.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {

    @Autowired
    private FileService fileService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView uploadFile(@RequestParam("file") MultipartFile multipartFile){
        long fileSize = multipartFile.getSize();
        String fileName = multipartFile.getOriginalFilename();
        ModelAndView modelAndView = new ModelAndView("upload-success");
        if(fileService.saveFile(multipartFile)){
            Map modelMap = new HashMap<>();
            modelMap.put("fileName", fileName);
            modelMap.put("fileSize", fileSize);
            modelAndView.addAllObjects(modelMap);
            return modelAndView;
        }
        return new ModelAndView("upload-failed");
    }

}

3. Create a File Service

Create a class that will save the file in the file system. In this example, the files are being saved in
C:\Javapointers.

package com.javapointers.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service("fileService")
public class FileService {

    public static final String SAVE_LOCATION = "C:/Javapointers/";

    public boolean saveFile(MultipartFile multipartFile){
        boolean result = false;
        //set the saved location and create a directory location
        String fileName  = multipartFile.getOriginalFilename();
        String location = SAVE_LOCATION;
        File pathFile = new File(location);
        //check if directory exist, if not, create directory
        if(!pathFile.exists()){
            pathFile.mkdir();
        }

        //create the actual file
        pathFile = new File(location + fileName);
        //save the actual file
        try {
            multipartFile.transferTo(pathFile);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

4. Create your jsp file


Create an input element with the name file (as we have defined in @RequestParam(“file”)).


Here is our upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Upload Javapointers</title>
</head>
<body>

Browse And Upload your File


</body> </html>

5. Testing our File Upload in Spring MVC application

We now test our application. If the file successfully uploaded to the server, the request will be redirected to the successful page displaying the name of the file and its size.

upload file in spring mvc 1

upload file in spring mvc 2

Download Source Code Here!

Page 1 of 1312345...10...Last »