java - jetty servlet 将 uri 映射到文件

标签 java servlets jetty

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

相关文章:

java - 使用java删除cookie

maven jetty - org.mortbay.jetty 与 org.eclipse.jetty

java - 使用 Jetty/Jersey/Guice 提供静态内容

java - Spring & hibernate 配置(使用 Maven): java. lang.ClassNotFoundException : org. hibernate.cfg.Configuration

javascript - Wicket 口 6 : TextField cursor position moves when component updated

java - 矩阵求逆的简单算法

servlets - jetty 6 index.html 欢迎页面无法正常工作

java - 如何在EntityListener类中使用@Autowired?

java - 文件未找到异常

java - 使用ajax和java进行文件上传