Java: Simple HTTP Server application that responds in JSON

后端 未结 4 1364
一生所求
一生所求 2021-02-15 19:56

I want to create a very simple HTTP server application in Java.

For example, if I run the server on localhost in port 8080, and I make

4条回答
  •  情深已故
    2021-02-15 20:35

    If you are already familiar with servlet you do not need much to create a simple server to achieve what you want. But I would like to emphasize that your needs will likely to increase rapidly and therefore you may need to move to a RESTful framework (e.g.: Spring WS, Apache CXF) down the road.

    You need to register URIs and get parameters using the standard servlet technology. Maybe you can start here: http://docs.oracle.com/cd/E13222_01/wls/docs92/webapp/configureservlet.html

    Next, you need a JSON provider and serialize (aka marshall) it in JSON format. I recommend JACKSON. Take a look at this tutorial: http://www.sivalabs.in/2011/03/json-processing-using-jackson-java-json.html

    Finally, your code will look similar to this:

    public class Func1Servlet extends HttpServlet {
      public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    
        String p1 = req.getParameter("param1");
        String p2 = req.getParameter("param2");
    
        // Do Something with the params
    
        ResponseJSON resultJSON = new ResponseJSON();
        resultJSON.setProperty1(yourPropert1);
        resultJSON.setProperty2(yourPropert2);
    
        // Convert your JSON object into JSON string
        Writer strWriter = new StringWriter();
        mapper.writeValue(strWriter, resultJSON);
        String resultString = strWriter.toString();
    
        resp.setContentType("application/json");
        out.println(resultString );
      }
    }
    

    Map URLs in your web.xml:

    
      func1Servlet
      myservlets.func1servlet
    
    
      func1Servlet
      /func1/*
    
    

    Keep in mind this is a pseudo-code. There are lots you can do to enhance it, adding some utility classes, etc...

    Nevertheless, as your project grows your need for a more comprehensive framework becomes more evident.

提交回复
热议问题