user3629892
user3629892

Reputation: 3046

embedded jetty: get post parameters

I am using embedded jetty like this:

    Server server = new Server(7498);

    URL url = Main.class.getClassLoader().getResource("html");

    URI webRootUri = null;
    try {
        webRootUri = url.toURI();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ServletContextHandler context = new ServletContextHandler(
            ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    try {
        context.setBaseResource(Resource.newResource(webRootUri));
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    context.setWelcomeFiles(new String[] { "index.html" });

    ServletHolder holderPwd = new ServletHolder("default",
            DefaultServlet.class);
    holderPwd.setInitParameter("cacheControl", "max-age=0,public");
    holderPwd.setInitParameter("useFileMappedBuffer", "false");
    holderPwd.setInitParameter("dirAllowed", "true");
    context.addServlet(holderPwd, "/");

    server.setHandler(context);

    try {
        server.start();
        //            server.dump(System.err);
    } catch (Exception e1) {
        e1.printStackTrace();
    }

I. e. I am pointing to static resources in my src/main/resources folder.

How do I handle post parameters now? I am issuing an ajax post request.

I know my ServletContextHandler has a handle method. Do I need to create my own class extending the ServletContextHandler?

Upvotes: 3

Views: 3148

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49515

You are using a ServletContextHandler, a common setup.

  1. create a new HttpServlet for yourself
  2. add it to the ServletContextHandler under a (servlet) url-pattern that you want
  3. have it override the .doPost() method
  4. read the request parameters for the POST request
  5. process them accordingly
  6. produce a response

What the step #2 change looks like in your main() to your ServletContextHandler ...

context.addServlet(MyPostServlet.class, "/api");

The MyPostServlet.java could look like this

public class MyPostServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // Get POST parameters
        String val = req.getParameter("foo");
        // Do something with 'foo'
        String result = backend.setValue("foo", val);
        // Write a response
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().printf("foo = %s (result: %s)%n",val,result);
    }
}

Upvotes: 2

Related Questions