1

I'm working on a project and I'm trying to get an HTML form data into my REST web service, so I can insert it into my database, I don't know where to get the HTML form data from.

This is my web service:

package hananepkg;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

/**
 * REST Web Service
 *
 * @author mon pc
 */
@Path("generic")
public class GenericResource {
    DBConnector db = new DBConnector();
    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of pkg.GenericResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces(MediaType.TEXT_HTML)
    
    public String insert(@QueryParam ("name")String name,@QueryParam ("email")String email,@QueryParam ("password")String password,@QueryParam ("confirmpassword")String confirmpassword) {
        //TODO return proper representation object
        
        return "<html><body><h1>"+db.insertData(name,email,password,confirmpassord)+"</body></h1></html>";
    }

    /**
     * PUT method for updating or creating an instance of GenericResource
     * @param content representation for the resource
     */
    
    @PUT
    @Consumes(MediaType.TEXT_HTML)
    public void putHtml(String content) {
    }
}

This is my html page:

<section id="contact" class="contact3">
        <div class="container" data-aos="fade-up">
  
          <div class="section-title">
            <h2>Sign In</h2>
          </div>

  
            <div class="col-lg-6 mt-5 mt-lg-0" data-aos="fade-left" data-aos-delay="100">
  
              <form action="forms/contact.php" method="post" role="form" class="php-email-form">
                <div class="form-row">
                    <div class="col-md-6 form-group">
                      <input type="text" name="name" class="form-control" id="name" placeholder="Username" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
                      <div class="validate"></div>
                    </div>
                    <div class="col-md-6 form-group">
                      <input type="email" class="form-control" name="email" id="email" placeholder="Email" data-rule="email" data-msg="Please enter a valid email" />
                      <div class="validate"></div>
                    </div>
                  </div>
                <div class="form-group">
                  <input type="password" class="form-control" name="subject" id="password" placeholder="Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
                  <div class="validate"></div>
                </div>
                <div class="form-group">
                    <input type="password" class="form-control" name="subject" id="confirmpassword" placeholder="Confirm Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
                    <div class="validate"></div>
                  </div>
                <div class="text-center"><button id="submit" type="submit">Sign In</button></div>
              </form>
  
            </div>
  
          </div>
  
        </div>
      </section>

<script type="text/javascript">
            $(document).ready(function() {
                $("#submit").click(function(event) {
                    event.preventDefault();

        $.ajax({
            type: "POST",
            url:  "http://localhost:8080/HananeTest/",
            data: formToJSON(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) 
            {
                alert('Success');
            },
            error: function(jqXHR, textStatus, errorThrown) 
            {
                alert('Error: ' + textStatus);
            }
        });
    });
});

    function formToJSON() 
    {
        return JSON.stringify
        ({
            "username": $('#name').val(),
            "email": $('#email').val(),
            "password": $('#password').val()
            "password": $('#confirmpassword').val()   });
    };
     
    </script>

Any suggestions how to get the input data into my web service so I can insert it to my database?

Matt
  • 12,848
  • 2
  • 31
  • 53
Han Ane
  • 33
  • 1
  • 6
  • Check if the path is correct. In your resource you have `generic` and in JS you have `HananeTest`. Your `formToJSON` does not fill the parameter `confirmpassword` but has a duplicate entry for `password`. – Matt Jan 17 '21 at 12:57
  • I changed the path from ```@path('generic')``` to ```@path('HananeTest')``` and in the function ```formToJSON``` I forgot to added ```"confirmpassword": $('#confirmpassword').val()``` – Han Ane Jan 17 '21 at 13:06
  • But how can I add the form input data into my insert Method in my web service ? – Han Ane Jan 17 '21 at 13:08
  • In the JS you are currently using a JSON string and in your service you are referring to individual query parameters. To get JSON data to your method, you can annotate it with `@Consumes({MediaType.APPLICATION_JSON})` and then use a simple POJO with the corresponding fields as parameter. – Matt Jan 17 '21 at 13:24
  • I changed ```@Produces(MediaType.TEXT_HTML)``` to ```@Consumes({MediaType.APPLICATION_JSON})``` but what you mean by simple POJO with the corresponding fields as parameter ? What I must change in ```insert Method``` ? – Han Ane Jan 17 '21 at 13:32

1 Answers1

0
  • In your resource you have generic and in JS you have HananeTest as path. Make sure your are using the correct paths on both sides.

  • Your formToJSON function does not fill the parameter confirmpassword but has a duplicate entry for password. Make sure that all the parameters are set properly.

  • In JS you are currently using a JSON string and in your service you are referring to individual query parameters. To get JSON data to your method, you can annotate it with @Consumes({MediaType.APPLICATION_JSON}) and then use a simple POJO with the corresponding fields as attributes.

    Example:

    @Path("api/user")
    public class YourResource {
    
        @GET
        @Consumes({MediaType.APPLICATION_JSON})
        @Produces(MediaType.TEXT_HTML) // depending on what you want to return
        public String insert(UserDTO user) {
            // validation logic
            // insert user into database
            // return something
        }
    }
    
    public class UserDTO {
    
        private String username;
        private String email;
        private String password;
        private String confirmpassword; // can possibly be removed if you check in JS whether the passwords match
    
        // getters and setters
    }
    
Matt
  • 12,848
  • 2
  • 31
  • 53
  • How can i test if it work ? I inserted some data in my html form but when I check the database , it's empty – Han Ane Jan 17 '21 at 15:01
  • @HanAne Use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) or logger to see what is stored in the DTO. – Matt Jan 17 '21 at 15:09
  • I'm using netbeans and I don't now how to use debugger – Han Ane Jan 17 '21 at 15:16
  • is the method insert will look like this :```public String insert(DBConnector d) { d = new DBConnector(); return d.insertData(d.getName(),d.getEmail(),d.getPassword(),d.getConfirmpassword());}``` – Han Ane Jan 17 '21 at 15:17