我正在使用这样的嵌入式码头:
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();
}
予。即我指的是src/main/resources
文件夹中的静态资源。
如何处理帖子参数?我正在发出一个ajax帖子请求。
我知道我的ServletContextHandler
有handle
方法。我是否需要创建自己的类来扩展ServletContextHandler
?
答案 0 :(得分:2)
您使用的是ServletContextHandler
常用设置。
HttpServlet
ServletContextHandler
.doPost()
方法POST
请求您main()
ServletContextHandler
的{{1}}步骤#2的变化是什么......
context.addServlet(MyPostServlet.class, "/api");
MyPostServlet.java
看起来像这样
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);
}
}