Java: Simple HTTP Server application that responds in JSON

后端 未结 4 1352
一生所求
一生所求 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:53

    Run main to start the server on port 8080

    public class Main {
        public static void main(String[] args) throws LifecycleException {
            Tomcat tomcat = new Tomcat();
            Context context = tomcat.addContext("", null);
    
            Tomcat.addServlet(context, "func1", new HttpServlet() {
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                    Object response = func1(req.getParameter("param1"), req.getParameter("param2"));
    
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writeValue(resp.getWriter(), response);
                }
            });
            context.addServletMappingDecoded("/func1", "func1");
    
            tomcat.start();
            tomcat.getServer().await();
        }
    
        private static String[] func1(String p1, String p2) {
            return new String[] { "hello world", p1, p2 };
        }
    }
    

    Gradle dependencies:

    dependencies {
        compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '8.5.28' // doesn't work with tomcat 9
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
    }
    

提交回复
热议问题