gpt4 book ai didi

java - jetty servlet 将 uri 映射到文件

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:07 25 4
gpt4 key购买 nike

通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com