JSP没有看到CSS [英] JSP doesn't see CSS

查看:142
本文介绍了JSP没有看到CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个简单的Servlets + JSP项目。它的结构如下所示:

I'm trying to make a simple Servlets + JSP project. It's structure looks like this:

index.jsp:

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>App</title>
  <link rel="stylesheet" type="text/css" href="../css/style.css"/>
</head>
<body>
<h1>Header</h1>
</body>
</html>

style.css:

style.css:

body {
    background-color: beige;
}

web.xml:

<web-app>
    <display-name>App</display-name>

    <servlet>
        <servlet-name>IndexServlet</servlet-name>
        <servlet-class>com.example.web.IndexServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>IndexServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

当我启动应用程序并在浏览器中打开它时,我看到index.jsp页面,但它的背景是白色所以css不工作那里。
可能是什么问题?

When I start the application and open it in the browser I see the index.jsp page but it's background is white so the css isn't working there. What could be the problem?

推荐答案

您的应用程序有两个问题:

There are two problems in your app:


  1. 在JSP中,您应该使用 $ {pageContext.request.contextPath} 为您的网址。有了这个,你可以确定你将使用绝对路径,而不是你的URL的相对路径。所以,这:

  1. In JSP, you should use ${pageContext.request.contextPath} to append the base path for your URLs. With this, you can be sure you will use absolute path instead of relative path for your URLs. So, this:

<link rel="stylesheet" type="text/css" href="../css/style.css"/>

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css"/>

这也可以通过使用< c:url& code> from JSTL:

This can also be accomplished by using <c:url> from JSTL:

<link rel="stylesheet" type="text/css" href="<c:url value='/css/style.css' />"/>


  • 您的servlet映射到 。请注意,这包括对这种CSS文件的资源的简单请求。如果你没有成功地处理这些请求,你可能会得到一个错误响应或一个空响应或其他什么,这取决于你如何处理servlet中的CSS文件的请求。我建议您更改您的servlet的网址格式,以映射到特定路径。

  • Your servlet is mapping to every request made in your app. Note that this includes simple requests for resources like this CSS file. If you're not handling these requests successfully, you may get an error response or an empty response or whatever, depends on how you handle the request for CSS files in the servlet. I recommend you to change the URL pattern for your servlet to map to specific paths instead.

    <servlet-mapping>
        <servlet-name>IndexServlet</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>
    


  • 这篇关于JSP没有看到CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆