Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resteasy @FormParam returns always null

Can anyone please help me with this.

I created a web service using resteasy with wildfly 8.1.0 but @FormParam always returns null.

UserService.java

Path("/user")
@Produces(MediaType.APPLICATION_JSON)
public class UserService {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/create")
    public String create(@FormParam("first_name") String firstName, @FormParam("last_name") String lastName,
            @FormParam("email") String email, @FormParam("username") String username,
            @FormParam("password") String password, @FormParam("address") String address,
            @FormParam("country") String country, @FormParam("zip") String zip, @FormParam("ssnlast4") String ssnlast4,
            @FormParam("mobile") String mobile, @FormParam("dob_month") String dobMonth,
            @FormParam("dob_year") String dobYear, @FormParam("reg_type") String regType,
            @FormParam("avatar") String avatar) {

        String str = firstName  + ":" + lastName + ":" + email + ":" + username + ":" + password + ":" + address + ":" + country + ":" + zip+ ":" + ssnlast4 + ":" + mobile;
        return str;
    }
}

I use POSTMAN to test the service. enter image description here

return will be {null:null:null:null:null:null:null:null:null:null}

Thanks. I appreciate it.

like image 380
blitzen12 Avatar asked Jan 15 '15 06:01

blitzen12


2 Answers

@FormParam is for application/x-www-form-urlencoded content type. The form-data button you selected in Postman will create mulitpart data. These are two different animals.

If you want your example to work, you should select the x-www-form-urlencoded button, then start adding key/value pairs. The key will be the @FormParam("key") that inject the value.

Also I would annotate your method with @Consumes(MediaType.APPLICATION_FORM_URLENCODED) so that any request with a content type that is not application/x-www-form-urlencoded will fail.

If you do want to use multipart data, then that's a different story. We can go down that path, if you confirm that is what you wanted. I don't see it being useful here though.

As an aside, you can click the Preview button and you will see the major difference in the body of how each type is sent.

like image 78
Paul Samsotha Avatar answered Oct 29 '22 12:10

Paul Samsotha


In our case the ContainerRequestFilter.filter(ContainerRequestContext) was calling containerRequestContext.getEntityStream() which seems to flush the buffer, and this caused the @FormParams to be null.

As a solution we send authentication token in header(ContainerRequestContext.getHeaders()) with the ajax request, which don't deal with the EntityStream.

like image 2
Nick Minchev Avatar answered Oct 29 '22 14:10

Nick Minchev