摘要:[Spring MVC] Static resources 設定方式 img/css/js
練習Spring MVC 時,遇到找不到圖檔或CSS的路徑問題。
若利用MVC方式取的path感覺也很麻煩,
等於要傳到controller再getresource()回傳path
沒試過但也不想試XDD。
google後發現最直覺的方式則是從spring 設定檔下手
serlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.ww.studio.controller" />
<bean id="teamService" class="com.ww.studio.impl.TeamServiceImpl" />
<!-- Default View Resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="true" />
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/resources/css/" />
<mvc:annotation-driven />
</beans>
主要是在</beans> 上需加入參數
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
以及內容指定spring maping 路徑
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
然後頁面語法為
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">
<title>Insert title here</title>
</head>
<body>
<img src="<c:url value="/resources/images/1.jpg" />">
</body>
</html>
即可以取得css/img/js等靜態檔案。