java 如何使用 VERTX 处理程序获取 POST 表单数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14390322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:06:03  来源:igfitidea点击:

How to get POST form data using VERTX handlers?

javavert.xformshttp-post

提问by iCodeLikeImDrunk

I am able to get the form data using the buffer handler, but it is a void function and I cannot return the form data values. Have about 4-7 forms total, I don't want to end up writing the same handler over and over because the default function is void.

我能够使用缓冲区处理程序获取表单数据,但它是一个空函数,我无法返回表单数据值。总共有大约 4-7 个表单,我不想最终一遍又一遍地编写相同的处理程序,因为默认函数是无效的。

html:

html:

<!DOCTYPE html>
<html>    
<head><title>Login Page</title></head>
<body>
    <a href="/activateUserPage">activate user</a>
    <br/>
    <a href="/login">log in</a>
    <br/>

    <form id='login' action='/login' method='post'>
        <fieldset >
            <legend>Login</legend>
            <input type='hidden' name='submitted' id='submitted' value='1'/>

            <label for='username' >UserName: </label>
            <input type='text' name='username' id='username'  maxlength="50"/>

            <label for='password' >Password: </label>
            <input type='password' name='password' id='password' maxlength="50"/>

            <input type='submit' name='Submit' value='Submit' />
        </fieldset>
    </form>         
</body>    
</html>

java:

爪哇:

import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.deploy.Verticle;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: yao
 * Date: 1/17/13
 * Time: 2:22 PM
 */

public class Main extends Verticle
{
    @Override
    public void start() throws Exception
    {
        System.out.println("starting the vertx stuff");
        final String host = "localhost";
        final String port = "8181";

        Vertx vertx = Vertx.newVertx();
        HttpServer httpServer = vertx.createHttpServer();

        ...

        httpServer.requestHandler(new Handler<HttpServerRequest>()
        {
            public void handle(HttpServerRequest req)
            {
                String path = req.path;

                /* start mapping of page urls*/
                // redirect user to the login page
                if (path.equals("/"))
                {
                    req.response.sendFile(dir + "html/loginPage.html");
                }
                ...

                /* end mapping of page urls*/

                /* start mapping of form urls */
                // login
                else if (path.equals(login))
                {
                    mainLogin();
                    getFormData(req);
                }
                ...

                /* end mapping of form urls */

                /* all other pages */
                else
                {
                    req.response.end("404 - page no exist");
                }
            }
        });

        System.out.println("vertx listening to: " + host + " " + port);
        httpServer.listen(Integer.valueOf(port), host);
    }

    ...

    private void getFormData(final HttpServerRequest req)
    {
        req.bodyHandler(new Handler<Buffer>()
        {
            @Override
            public void handle(Buffer buff)
            {
                String contentType = req.headers().get("Content-Type");
                if ("application/x-www-form-urlencoded".equals(contentType))
                {
                    QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                    Map<String, List<String>> params = qsd.getParameters();
                    System.out.println(params);
                }
            }
        });
    }
}

采纳答案by iCodeLikeImDrunk

what i did in the end is basically this:

我最后所做的基本上是这样的:

do the ajax call using post, the data from the form needs to be serialized.

使用 post 进行 ajax 调用,表单中的数据需要序列化。

$.ajax
({
    type: "POST",
    url: "/login",
    data: $('#frm_login').serialize(),
    success: function(data)
...

in the backend, vertx receives this data as a buffer. rest is to parse the buffer by splitting by "&" and "=".

在后端,vertx 将这些数据作为缓冲区接收。剩下的就是通过“&”和“=”分割来解析缓冲区。

Map<String, String> params = new HashMap<String, String>();
String[] paramSplits = buffer.toString().split("&");
String[] valueSplits;

if (paramSplits.length > 1)
{
    for (String param : paramSplits)
    {
        valueSplits = param.split("=");
        if (valueSplits.length > 1)
        {
            // add this check to handle empty phone number fields
            params.put(decode(valueSplits[0]), decode(valueSplits[1]));
        }
    }
}

hope this will help others!

希望这会帮助其他人!

回答by Parantap Sharma

Nowadays BodyHandler is provided by vertx, using it isExpectMultipart will be set to true and you will be able to read form attributes as

现在 BodyHandler 是由 vertx 提供的,使用它 isExpectMultipart 将被设置为 true,你将能够读取表单属性作为

request.getFormAttribute("username");//to read input named username.

just add this line before your actual handler:

只需在您的实际处理程序之前添加此行:

router.route().handler(BodyHandler.create());

回答by Redman

For java this worked perfectly:

对于java,这非常有效:

request.expectMultiPart(true);
    request.endHandler(req->{
      String text = request.formAttributes().get("bigtext"); 
      //got it here
      //do something ...
 });

回答by Kevin Bayes

This can be done using the formAttributes on the http request. Here is an example in scala

这可以使用 http 请求上的 formAttributes 来完成。这是 Scala 中的一个例子

  req.expectMultiPart(true) //Will expect a form
  req.endHandler({

    req.formAttributes() //This is used to access form attributes

    //some code with attributes

  })

Reference: http://vertx.io/core_manual_java.html#handling-multipart-form-attributes

参考:http: //vertx.io/core_manual_java.html#handling-multipart-form-attributes