有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Eclipse中的java Servlet将静态内容放在何处

在使用Eclipse编写servlet时,我应该将静态内容(图像、CSS等)放在哪里,这样我就可以将HTML链接到它(例如<img src="http://localhost:8080/context/image.png>)。我试着把它放到WebContent目录中,但没有成功(或者我不知道如何链接到它,我试过了<img src="image.png"><img src="http://localhost:8080/context/image.png">

我附上了我的项目浏览器的图片,所以你可以对它进行排序。 http://i.imgur.com/CwtCQVO.png


为了便于查找,以下是我在评论或其他地方发布的所有内容:


共 (3) 个答案

  1. # 1 楼答案

    首先,不要在你的链接中硬编码你的上下文,如果你的上下文路径被改变,这会使你以后很难改变链接。相反,使用EL创建相对路径:

    <img src="${pageContext.request.contextPath}/img/abc.png" />
    

    其次,我在您的WebContent中没有看到任何图像,如果您手动将图像放入窗口文件夹,则需要刷新eclipse项目,以便eclipse检测所有添加的文件。右键单击Project Explorer中的项目并选择Refresh

  2. # 2 楼答案

    试一试

    <img src="/context/image.png">
    

    但这取决于您如何部署应用程序。无论如何,像图像这样的文件必须在WebContent文件夹中

  3. # 3 楼答案

    创建一个test.html文件,并将其放置在Eclipse项目中的/Blog/WebContent/test.html

    <html>
     <head>
      <title>Test WebContent</title>
     </head>
     <body>
      <img src="images/test.png" />
     </body>
    </html>
    

    另外,在/Blog/WebContent/images文件夹中放置一个test.png图像文件

    现在,将浏览器指向http://localhost:8080/<your-web-app-name>/test.html并检查test.png是否得到渲染。如果是,那么问题在于从servlet编写HTML输出的方式

    对于配置为

    <servlet>
        <servlet-name>ImgServlet</servlet-name>
        <servlet-class>pkg.path.to.ImgServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ImgServlet</servlet-name>
        <url-pattern>/ImgServlet</url-pattern>
    </servlet-mapping>
    

    您的doGet()方法应该将HTML输出为

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html><head><title>Test WebContent</title></head>" +
                "<body><img src=\"images/test.png\" /></body></html>");
    

    编辑:要打印servlet接收到的所有请求参数,请在handleRequest()方法调用之前添加以下内容(您也可以对其进行注释以进行测试)

    PrintWriter out = response.getWriter();
    Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String param = (String) parameterNames.nextElement();
        out.println(param + " = [" + request.getParameter(param) + "]");
    }