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?
You are using a ServletContextHandler, a common setup.
HttpServlet for yourselfServletContextHandler under a (servlet) url-pattern that you want.doPost() methodPOST requestWhat 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With