Java webserver to respond with JSON -


i trying create simple java web-app responds request /test json string.

my environment java, intellij , tomcat 8.5.4.

so far have 3 classes already:

  • csv - csv json conversion
  • cleanup - class convert data
  • servlet - class responds request

my servlet class:

import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception;   @webservlet(name = "servlet") public class servlet extends httpservlet { protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {  }  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {     system.out.println("get request received");     cleanup cleanup = new cleanup();     cleanup.cleanupdata();      // logic needed here send data client      } } 

the cleanup class sends resulting data console like:

        objectmapper mapper = new objectmapper();         mapper.enable(serializationfeature.indent_output);         mapper.writevalue(system.out, list); 

i farily new , not sure if want can done part of javax.http.servlet or dependency required?

your solution no doubt works you, in future may want update follows:

public class cleanup {   ...    public void cleanupdata(writer output) {      objectmapper mapper = new objectmapper();      mapper.enable(serializationfeature.indent_output);      mapper.writevalue(output, list);   }     ... } 

and

protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {     system.out.println("get response");     response.setcontenttype("application/json");     convertcsv cleanup = new convertcsv();     string outputdata = cleanup.cleanupdata(response.getwriter());     ... 

setting content type correctly make easier javascript process response without being mangled browser (because told html).

secondly writing json directly response improve scalability of servlet because eliminates copy of json you're creating in string variable. not make difference if json short, imagine if cleanupdata generating large amounts of output, such when list contains 1000s of entries.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -