브라우저는 JSP로 전달되는 서블릿을 호출 할 때 CSS, 이미지 및 링크와 같은 관련 리소스에 액세스하거나 찾을 수 없습니다.
JSP로 전달되는 서블릿이있을 때 CSS 및 이미지를로드하고 다른 페이지에 대한 링크를 만드는 데 문제가 있습니다. 내가 설정 한 경우 특히, <welcome-file>
에을 index.jsp
의 CSS로드되고 있으며, 내 이미지가 표시되고있다. 그러나 제어를 전달하는 내 <welcome-file>
를로 설정 하면 CSS가 적용되지 않고 내 이미지가 표시되지 않습니다.HomeServlet
index.jsp
내 CSS 파일은 web/styles/default.css
.
내 이미지는 web/images/
.
내 CSS에 다음과 같이 연결합니다.
<link href="styles/default.css" rel="stylesheet" type="text/css" />
다음과 같이 내 이미지를 표시하고 있습니다.
<img src="images/image1.png" alt="Image1" />
이 문제는 어떻게 발생하며 어떻게 해결할 수 있습니까?
업데이트 1 : 응용 프로그램의 구조와 도움이 될 수있는 기타 정보를 추가했습니다.
header.jsp
파일은 CSS에 대한 링크 태그가 들어있는 파일입니다. 은 HomeServlet
내로 설정 welcome-file
에서 web.xml
:
<welcome-file-list>
<welcome-file>HomeServlet</welcome-file>
</welcome-file-list>
서블릿은 다음과 같이 선언되고 매핑됩니다 web.xml
.
<servlet>
<servlet-name>HomeServlet</servlet-name>
<servlet-class>com.brianblog.frontend.HomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
업데이트 2 : 마침내 문제를 발견했습니다-내 서블릿이 잘못 매핑되었습니다. 분명히 서블릿을 설정할 때 <welcome-file>
URL 패턴을 가질 수 없습니다 /
.
새 매핑은 다음과 같습니다.
<servlet-mapping>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/HomeServlet</url-pattern>
</servlet-mapping>
JSP 파일에 의해 생성 된 HTML 페이지의 모든 상대 URL은 예상대로 서버 측의 JSP 파일 위치가 아니라 현재 요청 URL (브라우저 주소 표시 줄에 표시되는 URL)에 상대적 입니다. 즉, 어떻게 든 디스크에서 리소스를 포함해야하는 웹 서버가 아니라 URL별로 리소스를 개별적으로 다운로드해야하는 웹 브라우저입니다.
JSP 파일의 위치 대신 서블릿의 URL을 기준으로 상대 URL을 변경하는 것 외에도이 문제를 해결하는 또 다른 방법은 도메인 루트에 대해 상대 URL을 만드는 것입니다 (예 :로 시작 /
). 이렇게하면 서블릿의 URL을 변경할 때 상대 경로를 다시 변경하는 것에 대해 걱정할 필요가 없습니다.
<head>
<link rel="stylesheet" href="/context/css/default.css" />
<script src="/context/js/default.js"></script>
</head>
<body>
<img src="/context/img/logo.png" />
<a href="/context/page.jsp">link</a>
<form action="/context/servlet"><input type="submit" /></form>
</body>
However, you would probably like not to hardcode the context path. Very reasonable. You can obtain the context path in EL by ${pageContext.request.contextPath}
.
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/default.css" />
<script src="${pageContext.request.contextPath}/js/default.js"></script>
</head>
<body>
<img src="${pageContext.request.contextPath}/img/logo.png" />
<a href="${pageContext.request.contextPath}/page.jsp">link</a>
<form action="${pageContext.request.contextPath}/servlet"><input type="submit" /></form>
</body>
(which can easily be shortened by <c:set var="root" value="${pageContext.request.contextPath}" />
and used as ${root}
elsewhere)
Or, if you don't fear unreadable XML and broken XML syntax highlighting, use JSTL <c:url>
:
<head>
<link rel="stylesheet" href="<c:url value="/css/default.css" />" />
<script src="<c:url value="/js/default.js" />"></script>
</head>
<body>
<img src="<c:url value="/img/logo.png" />" />
<a href="<c:url value="/page.jsp" />">link</a>
<form action="<c:url value="/servlet" />"><input type="submit" /></form>
</body>
Either way, this is in turn pretty cumbersome if you have a lot of relative URLs. For that you can use the <base>
tag. All relative URL's will instantly become relative to it. It has however to start with the scheme (http://
, https://
, etc). There's no neat way to obtain the base context path in plain EL, so we need a little help of JSTL here.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="uri" value="${req.requestURI}" />
<c:set var="url">${req.requestURL}</c:set>
...
<head>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
<link rel="stylesheet" href="css/default.css" />
<script src="js/default.js"></script>
</head>
<body>
<img src="img/logo.png" />
<a href="page.jsp">link</a>
<form action="servlet"><input type="submit" /></form>
</body>
This has in turn (again) some caveats. Anchors (the #identifier
URL's) will become relative to the base path as well! You would like to make it relative to the request URL (URI) instead. So, change like
<a href="#identifier">jump</a>
to
<a href="${uri}#identifier">jump</a>
Each way has its own pros and cons. It's up to you which to choose. At least, you should now understand how this problem is caused and how to solve it :)
See also:
I faced similar issue with Spring MVC application. I used < mvc:resources >
tag to resolve this issue.
Please find the following link having more details.
http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/
You must analyse the actual HTML output, for the hint.
By giving the path like this means "from current location", on the other hand if you start with a /
that would mean "from the context".
Your welcome page is set as That Servlet . So all css , images path should be given relative to that servlet DIR . which is a bad idea ! why do you need the servlet as a home page ? set .jsp as index page and redirect to any page from there ?
are you trying to populate any fields from db is that why you are using servlet ?
If you are using Spring MVC, then you need to declare default action servlet for static contents. Add the following entries in spring-action-servlet.xml. It worked for me.
NOTE: keep all the static contents outside WEB-INF.
<!-- Enable annotation-based controllers using @Controller annotations -->
<bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="0" />
</bean>
<bean id="controllerClassNameHandlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="order" value="1" />
</bean>
<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
As for your update, I was confused for the reasoning behind in. Dug a little deeper and found this gem:
- yoursite.com becomes yoursite.com/
- yoursite.com/ is a directory, so the welcome-file-list is scanned
- yoursite.com/CMS is the first welcome-file ("CMS" in the welcome-file-list), and there is a mapping of /CMS to the MyCMS servlet, so that servlet is accessed.
Source: http://wiki.metawerx.net/wiki/HowToUseAServletAsYourMainWebPage
So, the mapping then does make sense.
And one can now freely use ${pageContext.request.contextPath}/path/ as src/href for relative links!
short answer - add following line in the jsp which will define the base
base href="/{root of your application}/"
Below code worked for me.
instead of use <%@ include file="styles/default.css"%>
'code' 카테고리의 다른 글
열 지향 NoSQL은 문서 지향과 어떻게 다릅니 까? (0) | 2020.10.17 |
---|---|
종속성이있는 AngularJS 팩토리 단위 테스트 (0) | 2020.10.17 |
MySQLdb를 사용하여 커서를 닫는 경우 (0) | 2020.10.17 |
자바 메소드 호출 비용 (0) | 2020.10.17 |
JavaScript-문자열 일치에 변수 사용 (0) | 2020.10.16 |