通过 HttpServletRequest.getRequestURI
,我们可以获取用户访问 servlet 时输入的路径。
如何编写一个 servlet 将这些 URI 映射到我的主目录中的文件。例如,如果用户输入 servlet 的 URL
"http://localhost:8080/webbtechnologies/html/index.html"
发送文件
C: \ Users \ User \ My Documents \ Web Technologies \ html \ index.html
给用户。
这是我到目前为止的代码:
public class SimpleFileManagerServlet extends HttpServlet {
private String location;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=UTF-8");
resp.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = resp.getWriter();
location = req.getRequestURI();
}
public static void main(String... args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(SimpleFileManagerServlet.class, "/");
Server server = new Server(8080);
server.setHandler(context);
server.start();
server.join();
}
}
最佳答案
看看jetty的DefaultServlet,它完全符合你的要求。如果您想做其他事情,您只需使用 DefaultServlet 中的代码并扩展它即可。
但是,给出您的用例 DefaultServlet 的描述对您来说应该足够了。
这是 javadoc:http://download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/servlet/DefaultServlet.html
查看随发行版一起提供的测试 Web 应用程序,了解如何在 web.xml 中对其进行配置等。
关于java - jetty servlet 将 uri 映射到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13729826/