SpringMvc framework static resource access configuration

1. In the springmvc framework, importing static resources into the jsp page keeps reporting errors:

jsp page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> 
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<img alt="测试" src="<%=basePath%>image/bg.jpg" />
</body>
</html>


警告: No mapping found for HTTP request with URI [/spring10.5/image/bg.jpg] in DispatcherServlet with name 'springMVC'


Solution:

1.  <servlet-mapping>  
    <servlet-name>springMVC</servlet-name>  
    <url-pattern>/</url-pattern>  
  </servlet-mapping>  
  
 <servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.gif</url-pattern>


 </servlet-mapping>
 <servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.jpg</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.js</url-pattern>
 </servlet-mapping>

Solution 2 : Add the following line to the spring configuration file:

<mvc:default-servlet-handler/>

Note that it needs to be spring3.0.5 or later

Solution 3

<!-- HandlesHTTP GET requests for /resources/** by efficiently serving up static resourcesin the ${webappRoot}/resources directory –>

<mvc:resourcesmapping="/resources/**" location="/resources/" cache-period="31536000"/>

This configuration tells spring how to handle static resources.


Supplementary method: When configuring springmvc: when defining the view resolver, static resources can also be configured together

   <!-- Access to static resources (js/image/css) -->  
    <mvc:resources location="/js/" mapping="/js/**"/>  
     <mvc:resources location="/image/ " mapping="/image/**"/>  
     <mvc:resources location="/css/" mapping="/css/**"/>  

Guess you like

Origin blog.csdn.net/qi95719/article/details/52985988