Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from form with spark java?

I'm pretty new with all these things but hope that you guys can help me understand how does it work. I got a form with field . How do i get data from client back? Was looking for some information but couldnt find.

<form action="Dispatcher" method="post">
    <fieldset>
        <p>Name</p>
        <input type="text" name="userName" required="true">

        <p>Email</p>
        <input type="text" name="userEmail" required="true">
        <input type="submit" value="submit">
    </fieldset>
</form>
like image 408
Bartłomiej Niemiec Avatar asked Mar 28 '15 00:03

Bartłomiej Niemiec


4 Answers

I faced the same issue. I used queryParams to solve it:

request.queryParams("userName")
like image 71
Stephan Avatar answered Nov 20 '22 06:11

Stephan


Just for the record, I faced a similar problem and this how I solved it.

Since it is a multipart request, you will have to specify that

MultipartConfigElement multipartConfigElement = new MultipartConfigElement(path);

req.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);

You can find the details here SparkJava: Upload file did't work in Spark java framework

Once this is done correctly you should be able to access the data using query params as mentioned Stephan.

like image 26
Pankaj Avatar answered Nov 20 '22 05:11

Pankaj


I think you need to use request.params("userName") which will give you the list of parameters submitted with name userName

like image 3
testinfected Avatar answered Nov 20 '22 07:11

testinfected


As Java doc says,

If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.

So request.queryParams("userName") won't work after calling request.body() (for logging for instance). I wrote a utility function to get parameter.

public static String getParameter(String body, String param) {
    HashMap<String, String> params = new HashMap();
    for (String s : body.split("&")) {
        String[] kv = s.split("=");
        params.put(kv[0], kv[1]);
    }
    String encoded = params.get(param);
    return URLDecoder.decode(encoded, StandardCharsets.UTF_8);
}
like image 1
Hanson Avatar answered Nov 20 '22 07:11

Hanson