1

HttpServletRequest.getRequestURIユーザーがサーブレットにアクセスするときに入力したパスを取得できます。

これらの URI をホーム ディレクトリ内のファイルにマップするサーブレットを作成するにはどうすればよいですか。たとえば、ユーザーがサーブレットの 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();
}


}
4

2 に答える 2

1

Have a look at jetty's DefaultServlet which exactly does what you want. In case you want to do additional things, you can just use the code from the DefaultServlet and extend it.

However giving your description of your use case DefaultServlet should be sufficient for you.

Here's the javadoc: http://download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/servlet/DefaultServlet.html

Have a look at the test webapp provided with the distribution on how to configure it in web.xml, etc.

于 2012-12-06T09:06:54.730 に答える
0

Jetty'sDefaultServletがこれを行います。本当に必要なのは、サーバー上のどこからファイルを提供するかを指定することだけです。

これを試して:

import org.eclipse.jetty.servlet.DefaultServlet;

public static void main(String... args) throws Exception {

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    context.setResourceBase("file:///C:/Users/User/My Documents/Web Technologies");
    context.setContextPath("/");
    context.addServlet(new ServletHolder("default", DefaultServlet.class), "/*");

    Server server = new Server(8080);
    server.setHandler(context);
    server.start();
    server.join();
}
于 2016-05-06T14:31:53.703 に答える