简体   繁体   中英

How do retrieve vales from HTML Post method to Java with freemarker?

I am trying to create a simple registration form and insert the data from the user into mongodb.

    <html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sign Up</title>
  <link href="/css/main.css" rel="stylesheet">
</head>
<body>
<h2>Sign Up</h2>
<#if user?? >
Your submitted data<br>
Name: ${user.user_id}<br>
Password: ${user.password}<br>
Email: ${user.email}<br>
<#else>
<form action="/form" method="post">
  First name:<br>
  <input type="text" name="Name">
  <br><br>
  Pasword:<br>
  <input type="text" name="password">
    <br><br>
  Email:<br>
  <input type="text" name="email">
  <br><br>
  <input type="submit" value="Submit">
</form>
</#if>
<script src="/js/main.js"></script>
</body>
</html>

I have a User class, and I want to create an instance of it, to fetch the data and insert it to mongodb. This is the part I don't know how to do. How do I create the controller to pass the data from HTML to the User instance?

This is what I have so far -

//sign up page
        Spark.get(new Route("signup") {
            @Override
            public Object handle(Request request, Response response) {
                StringWriter writer = new StringWriter();
                User user = new User(); // create user to fetch results
                try{
                    Template signupTemplate = configuration.getTemplate("signup.ftl");

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
            }

How do I go on from here? Can I do that only with freemarker and sparkjava ?

To post form data to server, you should define a spark route to listen for POST method.

A spark route comprises of three entities ( see doc's ),

  • verb: get, post, put, delete etc.
  • path: Request path for which the Route applies
  • callback: Handler class that will be invoked when the incoming request matches the path.

In your case it should be,

Spark.post("/form", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            // process request and return response
        }
    });

If your working with Java 8, you could simplify the above,

Spark.post("/form", (request, response) -> {
        // process request and return response
    });

Now to read form data, you could do so by fetching the raw request( HttpServletRequest ) and using getParameter() inside the handle method.

HttpServletRequest httpRequest = request.raw();
String name = httpRequest.getParameter("Name");
String email = httpRequest.getParameter("email");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM