Hyun Jung
Hyun Jung

Reputation: 69

When the argument is null as a parameter

The method as a controller in Java that I have written gets an File typed argument like below.

@RequestMapping(value = "/user/insertUser")
public String insertUser(@RequestParam("imageFile") CommonsMultipartFile file,
        HttpSession session) throws Exception {
......}

What my problem is that when there is no File argument sent from a JSP , how I can handle it. I am not sure if my explain was understandable though.

Upvotes: 1

Views: 955

Answers (6)

Sudam Jadhav
Sudam Jadhav

Reputation: 1

Here you can do this parameter as required = false so that you have option to sand this parameter or not.

{
    @RequestMapping(value = "/user/insertUser")
    public String insertUser(@RequestParam(value="imageFile",required=false) CommonsMultipartFile file,
        HttpSession session) throws Exception {
......}
}

using this, if you send "imageFile" then you will get on server, else you have not send "imageFile" then you will get it null.

Upvotes: 0

Vero J
Vero J

Reputation: 261

If your question is whether you can provide an optional parameter as request param, you can do that by simply changing your @RequestParam to below.

@RequestParam(value = "imageFile", required = false) CommonsMultipartFile file

If you are using Java 8 you can also do the below.

@RequestParam("imageFile") Optional<CommonsMultipartFile> file

If your question is not this then please provide more details.

Upvotes: 0

Jay Smith
Jay Smith

Reputation: 2480

You can do it as follows:

@RequestMapping(value = "/user/insertUser")
public String insertUser(@RequestParam("imageFile") CommonsMultipartFile file,
        HttpSession session) throws Exception {

        if(file!=null && !file.isEmpty()) {
           //file is uploaded successfully
        } else {
           //file is not uploaded
        }
}

Upvotes: 0

Pranay Kumbhalkar
Pranay Kumbhalkar

Reputation: 701

You need to give required = false for imageFile

@RequestMapping(value = "/user/insertUser")
public String insertUser(@RequestParam("imageFile", required = false) CommonsMultipartFile file,HttpSession session) throws Exception {
......}

Upvotes: 0

Raman Sahasi
Raman Sahasi

Reputation: 31841

You can set defaultValue to handle null case:

@RequestMapping(value = "/user/insertUser")
public String insertUser(@RequestParam(value = "imageFile",  required = false, defaultValue = "/default/path/to/file") CommonsMultipartFile file,
        HttpSession session) throws Exception {
......}

Upvotes: 4

mhasan
mhasan

Reputation: 3709

I believe you are trying to make it as optional you can do

 @RequestParam(value = "imageFile", required = false)

Upvotes: 0

Related Questions