How to return a Java object from a Servlet to a view in Response (HTML-Page, accept in ajax) ???

  • What does it mean to return in response ? - not a Programmer
  • ok, stuff in respons! - Vadym Doroshevych
  • one
    Do you want to display a Java object on an HTML page? - not a Programmer

1 answer 1

I figured out who needs it - here’s the code on the back! What would pass the object java to the presentation!

User user = new User(); user.setId(21); user.setName("John"); String json = new Gson().toJson(user); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(json); 

And to make out on representation -

  $.ajax({ "url": "http://localhost:8080/servletURL", 'method': 'get', 'success': function (response) { console.log(response); console.log(response.id); console.log(response.name); }, 'error': function (error) { console.log(JSON.parse(error)); } }); 
  • resp.setContentType("application/json") user will not see anything, he can "see" only the html page. json or xml return only web services. - not a Programmer
  • one
    @notaProgrammer So the author of this kind is not necessary. The response is processed by javascript. In the example, just out in the console displays. Clearly, we are talking about updating some fields in the view via ajax - Sergey
  • one
    Author note. There are more in the java restful webservice. Supports json right away. And now it is fashionable to do everything through rest. Servlet-s is now a basic level. And much is being done through add-ons on them for popular technologies. - Sergey
  • I know, in the spring, in general, without turning anything, everything is done. But given a task with servlets - should do) Thanks for the answers! P.S. The console is a simple example, so as not to break your head where the answer is inserted, etc. - Vadym Doroshevych