Spring MVC 4.2.2 中最好的集成静态资源的方法

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es)

本文遵循“署名-非商业用途-保持一致”创作公用协议

转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。

Spring MVC 4.2.2 – Best way to Add/Integrate JS, CSS and images into JSP file using ‘mvc:resources mapping’

Short link:

Last Updated on October 22nd, 2015 by Crunchify 2 Comments

Sometime back I’ve written a tutorial on Hello World Spring MVC. Spring MVC web is a model-view-control framework and you can find more information here.

As you could see Sayan and Arturo asked few questions while working on Spring MVC tutorial on how to add JavaScript/.js and CSS/.css file to their project.

Both .js and .css are static resources. Do you also have similar question like:

  • In spring mvc where to put css/js/img files?
  • Why my project can’t find css, images and js static files, etc?

In this tutorial we will go over all detailed steps on how to include both into your Spring MVC java project simplest way.

Let’s get started:

Below is an updated project structure for your reference.

Step-1

Please go ahead and implement your HelloWorld Spring MVC project by following all detailed steps. Make sure you have it working correctly.

Now, in below steps we are going to – create 1 folder, add 2 files, modify 2 files.

Step-2

Create resources folder under WebContent folder.

Step-3

Create crunchify.js file under resources folder.

crunchify.js

1

2

3

4

5

jQuery(document).ready(function($) {

$(‘#crunchifyMessage‘).html("<h4>This message is coming from ‘crunchify.js‘ file...</h4>")

});

Step-4

Create crunchify.css file under resources folder.

crunchify.css

1

2

3

4

5

6

h2{

color:#dd7127;

}

h4{

color:#DD2727;

}

Step-5

Modify welcome.jsp file with below content. Please checkout highlighted lines.

welcome.jsp

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<!DOCTYPE html>

<html>

<head>

<!-- let‘s add tag srping:url -->

<spring:url value="/resources/crunchify.css" var="crunchifyCSS" />

<spring:url value="/resources/crunchify.js" var="crunchifyJS" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<link href="{crunchifyCSS}" rel="stylesheet" />

<script src="${crunchifyJS}"></script>

<!-- Finish adding tags -->

<title>Spring MVC Tutorial by Crunchify - Hello World Spring MVC Example</title>

<style type="text/css">

body {

background-image: url(‘http://crunchify.com/bg.png‘);

}

</style>

</head>

<body>${message}

<br>

<div

style="font-family: verdana; padding: 10px; border-radius: 10px; font-size: 12px; text-align: center;">

<h2>Checkout this font color. Loaded from ‘crunchify.css‘ file under ‘/WebContent/resources/‘ folder</h2>

<div id="crunchifyMessage"></div>

<br> Spring MCV Tutorial by <a href="http://crunchify.com">Crunchify</a>.

<br> <br> Click <a

href="http://crunchify.com/category/java-web-development-tutorial/"

target="_blank">here</a> for all Java and <a

href=‘http://crunchify.com/category/spring-mvc/‘ target=‘_blank‘>here</a>

for all Spring MVC, Web Development examples.<br>

</div>

</body>

</html>

Here spring:url tag based on the JSTL c:url tag. This variant is fully backwards compatible with the standard tag. Enhancements include support for URL template parameters.

Step-6

Modify crunchify-servlet.xml file. Add below two lines at the bottom of file before </beans> tag.

1

2

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:annotation-driven />

Here is a complete file content:

crunchify-servlet.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.crunchify.controller" />

<bean id="viewResolver"

class="org.springframework.web.servlet.view.UrlBasedViewResolver">

<property name="viewClass"

value="org.springframework.web.servlet.view.JstlView" />

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:annotation-driven />

</beans>

mvc:resources configures a handler for serving static resources such as images, js, and, css files with cache headers optimized for efficient loading in a web browser. Allows resources to be served out of any path that is reachable via Spring’s Resource handling.

Step-7

  1. Perform Project -> Clean
  2. Re-deploy CrunchifySpringMVCTutorial application on Tomcat web server
  3. Visit URL: http://localhost:8080/CrunchifySpringMVCTutorial/welcome.jsp
  4. Check out the result

Before

After

Have anything to add to this article? Please chime in and join the conversion.

SHARE ON

TwitterFacebookGoogle+BufferPin ItFollow @Crunchify

Some more articles you might also be interested in …

  1. Spring MVC: How to Declare a Bean in Spring Application?
  2. Working on Spring MVC Project? How to Report List of All Loaded Spring Beans during Startup?
  3. Read config.properties value using Spring ‘singleton’ Scope in your Java Enterprise Application
  4. Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
  5. Spring MVC 4.1.X – Simple way to Send an Email using org.springframework.mail. javamail.JavaMailSenderImpl
  6. How to import all Spring MVC Dependencies to your Maven Project?
  7. Cannot be Read or is Not a Valid ZIP file – How to fix Maven Build Path Error with corrupted .jar file
  8. How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example
  9. Spring MVC: How to Access ModelMap Values in a JSP?
  10. How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)

Enjoyed this post?

Be sure to subscribe to the Crunchify newsletter and get regular updates about awesome posts just like this one and more! Join more than 13000 subscribers!

Enter your email address...

About Crunchify

Hello & Good Day from greater New York. Crunchify is founded by App Shah. He is a professional blogger & loves Web development hence Crunchify.com is his publication with more than 10 millions pageviews per month, that covers all aspects and tactics on Java, WordPress, J2EE (Enterprise Java), Spring MVC, Github, etc Technologies.

时间: 2024-10-12 20:53:43

Spring MVC 4.2.2 中最好的集成静态资源的方法的相关文章

关于Spring MVC 3.1.x中如何替换数据Converter的问题

参考的原文 http://www.cnblogs.com/yangzhilong/p/3725849.html 要解决的问题 Web API的开发中,经常需要对HTTP中的request body中的数据流绑定到自建Model中,或者将自建Model反序列化到Response Body中.这时候就需要用到这些Converter.而这些默认配置下的Converter可能得不到你想要的结果. 如何解决 这里仅对Json相关的转换做出说明.由于Spring默认使用的是jackson,而jackson的

Spring MVC 3 表单中文提交后乱码问题的解决方法

在spring mvc 3.0 框架中,通过JSP页面.HTML页面以POST方式提交表单时,表单的参数传递到对应的servlet后会出现中文显示乱码的问题.解决办法可采用spring自带的过滤技术,对所有页面间参数的传递设置统一的字符编码. 分两步解决问题: 1.设置页面格式为UTF-8 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 2.在web.xml中添加

spring mvc在web.xml中的配置

spring mvc将所有的请求都经过一个servlet控制器-DispatcherServlet,这个servlet的工作就是将一个客户端的request请求分发给不同的springmvc控制器,既然是一个控制器Servlet就需要在web.xml中配置. <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.Dispa

2017.3.31 spring mvc教程(三)请求映射(静态文件访问、拦截器)

学习的博客:http://elf8848.iteye.com/blog/875830/ 我项目中所用的版本:4.2.0.博客的时间比较早,11年的,学习的是Spring3 MVC.不知道版本上有没有变化比较大的功能. spring mvc教程(三)拦截器 1.Spring中的拦截器 (1)拦截器接口 Spring提供了拦截器接口.实现这个接口或继承这个类,就能实现自己的拦截器. 1 org.springframework.web.servlet.HandlerInterceptor接口 2 or

jquery easyui+spring mnv 样式引不进,需要加载静态资源

前台用的EasyUI,页面中引入了easyUI的js与css(引入路径正确),但是无论如何都显示不出来, 如下图: EasyUI的样式没有,看控制台:警告,找不到 [java] view plaincopyprint? 21:26:25,643 WARN [org.springframework.web.servlet.PageNotFound](http-localhost/127.0.0.1:8080-1) No mapping found for HTTP request with URI

【Java面试题】60 接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承具体类(concrete class)? 抽象类中是否可以有静态的main方法?

接口可以继承接口.抽象类可以实现(implements)接口,抽象类可以继承具体类.抽象类中可以有静态的main方法. 问:  抽象类是否可继承实体类 (concrete class) 答: 抽象类是可以继承实体类,但前提是实体类必须有明确的构造函数. 答案很明确,可以继承.其实从Object就是个实体类,Java的API文档里,每个抽象类的条目里都明确写着直接或间接继承自Object,所以这点是没有疑问的. 关键在于这答案里所说的"前提是实体类必须有明确的构造函数"一句,是什么意思.

15、接口是否可继承接口?抽象类是否可实现(implements)接口?抽象类是否可继承具体类(concreteclass)?抽象类中是否可以有静态的main方法?

接口可以继承接口.抽象类可以实现(implements)接口,抽象类可以继承具体类.抽象类中可以有静态的main方法. 问:  抽象类是否可继承实体类 (concrete class) 答: 抽象类是可以继承实体类,但前提是实体类必须有明确的构造函数. 答案很明确,可以继承.其实从Object就是个实体类,Java的API文档里,每个抽象类的条目里都明确写着直接或间接继承自Object,所以这点是没有疑问的. 关键在于这答案里所说的“前提是实体类必须有明确的构造函数”一句,是什么意思. 一般学习

spring mvc 删除返回字符串中值为null的字段

在spring的配置文件中进行一下配置: <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter

Spring MVC:在jsp中引入css

为了将css引入jsp中,今天可真是踩了好多坑,最后在stackoverflow上找到了解决方法,不多说贴出代码. 在web.xml中添加以下代码: <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> spring-servlet.xml配置如下: <?xml vers