0

I have a problem when trying to read the data that I sent to the server from client with ajax function.

To start, here is my ajax function;

$(document).ready(function(){

    $('#btnReg').click(function(){
            var email = document.getElementById('email').value;
            var korIme = document.getElementById('korIme').value;
            var lozinka = document.getElementById('pass1').value;

            $.ajax({
                type: 'POST', 
                url: 'http://localhost:8080/Web_Projekat/rest/korisnici/registracija',
                contentType: 'application/json',
                dataType: 'text', 
                data: formToJSON(korIme, lozinka, "Petar", "Petrovic", "Menadzer",  "06315487", email, "slika"), 
                success: function(){
                    alert("Success");
                },
                error: function(){
                    alert("Error");
                }
            });

        } else {
            return false;
        }


    });
});

function formToJSON(korIme, lozinka, ime, prezime, uloga, telefon, email, slika) {
    return JSON.stringify({
        "korIme" : korIme,
        "lozinka": lozinka,
        "ime": ime,
        "prezime": prezime,
        "uloga": uloga,
        "telefon": telefon,
        "email" : email,
        "slika": slika
    });
}

The data is sent successfully to the server. Here is my rest code:

@Path("/korisnici")
public class KorisnikServis {

    @Context
    HttpServletRequest request;
    @Context
    ServletContext ctx;

    @POST
    @Path("/registracija")
    @Consumes({ MediaType.APPLICATION_JSON})
    @Produces(MediaType.TEXT_PLAIN)
    public String registracija(String data) {
        return data;
    }
}

Sorry for the names of the classes cause they are not in english.

Now my question is: How can I parse the data that's sent and work with it? Because the variable data is just a string with json format. How can I extract let's say the email address that't sent from the client?

UPDATE I have added some jar files, and added action="" to my form. But now I get this error : "HTTP Status 415 - Unsupported Media Type" I am using apache tomcat 6

Thank you.

P3P5
  • 743
  • 3
  • 10
  • 28

4 Answers4

0

You can get data from ajax request in your controller servlet using following command

request.getParameter("emailAddress");

Above statement will give you email address set in ajax request.

Abhijeet
  • 3,163
  • 1
  • 17
  • 32
0

Add Class to handle form data

public class FormData {

String korIme;
String lozinka;
String ime;
String prezime;
String uloga;
String telefon;
String email;
String slika;

public FormData() {
    // TODO Auto-generated constructor stub
}    
public String getKorIme() {
    return korIme;
}
public void setKorIme(String korIme) {
    this.korIme = korIme;
}
public String getLozinka() {
    return lozinka;
}
public void setLozinka(String lozinka) {
    this.lozinka = lozinka;
}
public String getIme() {
    return ime;
}
public void setIme(String ime) {
    this.ime = ime;
}
public String getPrezime() {
    return prezime;
}
public void setPrezime(String prezime) {
    this.prezime = prezime;
}
public String getUloga() {
    return uloga;
}
public void setUloga(String uloga) {
    this.uloga = uloga;
}
public String getTelefon() {
    return telefon;
}
public void setTelefon(String telefon) {
    this.telefon = telefon;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getSlika() {
    return slika;
}
public void setSlika(String slika) {
    this.slika = slika;
}

}

Update your webservice

@POST
@Path("/registracija")
@Consumes({ MediaType.APPLICATION_JSON})
@Produces(MediaType.TEXT_PLAIN)
public String registracija(FormData data) {
data.email;/////this is email
    return data;
}
swan
  • 2,179
  • 3
  • 22
  • 47
  • I tried your way, and nothing. When ajax is called again it fires his error method. – P3P5 Sep 07 '16 at 11:30
0

You probably are looking for @BeanParam, take a look at this example, https://jersey.java.net/documentation/latest/user-guide.html#d0e2435

dvsakgec
  • 2,388
  • 2
  • 19
  • 29
0

Create a Java class (a POJO) and then use an ObjectMapper (Jackson etc -- yes, this requires adding additional libraries) to convert your json string into a POJO instance/object.

POJO

public class User {

   public User(){
   }

   private String ime;
   private String prezime;
   private String lozinka;

   //add other fields

   public String getIme(){
   return ime;
   }
   public void setIme(String ime){
   this.ime = ime;
   }

   //other getters/setters
   }


}

ObjectMapper

import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonParser {   
    ObjectMapper objectMapper=new ObjectMapper();
    public <T> T parseJson(String json,Class<T> targetType)throws Exception{                    
        objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, targetType);
    }
}

And then in your server method

@POST
@Path("/registracija")
@Consumes({ MediaType.APPLICATION_JSON})
@Produces(MediaType.TEXT_PLAIN)
public String registracija(String data) {

    JsonParser parser = new JsonParser();

    User myUser = parser.parseJson(data, User.class);
    //do whatever you want with myUser

    return data;
}

Note that if you add JSON libraries to your application, then Jersey should be able to do the conversion automatically, which means that you can rewrite your method to read

 @POST
    @Path("/registracija")
    @Consumes({ MediaType.APPLICATION_JSON})
    @Produces(MediaType.TEXT_PLAIN)
    public String registracija(User data) {
....
}
dsp_user
  • 1,625
  • 2
  • 12
  • 21
  • Thank you for your answer. But I know that it should work like this also. I have found out that if I remove String data as argument to the class registracija, and write it like this : public String registracija() and than just return some text, I get the success from ajax, but when add argument to the class I get error from ajax. Can it be that I'm not sending the data to the server correctly? – P3P5 Sep 07 '16 at 11:44
  • I'm not really sure but perhaps you can rewrite your ajax to submit a HTML form rather than send a variable (formatted as json). You can take a look http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form – dsp_user Sep 07 '16 at 11:53