简体   繁体   中英

How to retrieve json from javascript and pass to servlet and create a class from the data

I have a user edit form and when i submit im calling EditMain servlet.I have this javascript file from where i retrieve the data.

$(document).on("click","#main",function(){
    // Пример за заявка POST:
    postData('http://localhost:8080/javabeans/EditMain', toJSONString(document.forms[0]))
      .then((data) => {
        console.log(data); 
      });
});
async function postData(url = 'http://localhost:8080/javabeans/edit_profile.jsp', data = {}) {
      const response = await fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin', 
        headers: {
          'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer',
        body: data
      });
      return response.json();
}

   function toJSONString( form ) {
        var obj = {};
        var elements = form.querySelectorAll( "input, select, textarea" );
        for( var i = 0; i < elements.length; ++i ) {
            var element = elements[i];
            var name = element.name;
            var value = element.value;

            if( name ) {
                obj[ name ] = value;
            }
        }

        return JSON.stringify( obj );
    }

this is my servlet class where i get nullpointerException when i call the function fromJson

    response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String requestData = request.getReader().lines().collect(Collectors.joining());
        out.println(requestData);
        User u = gson.fromJson(requestData, User.class);
        out.println(u.getName());

and i see in the console that i get response but not in json format.What i get is this

name=asd&job=asd&description=asdasdsa%09%09%09%09%09%09Some+long+description.............%0D%0A%0D%0A%09%09%09%09%09

Looks like the response is text not json.

try

response.setContentType("application/json");

not

response.setContentType("text/html;charset=UTF-8");

You can see similar here: Servlet returning response as HTML instead of JSON

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