我知道这个问题有很多主题,因为我已经完成了所有这些问题。但我仍然没有找到任何解决方案。
基本上我有一个ResourceHandler来映射资源但是在进入jsp时没有找到css文件。我正在使用Spring 4.3.9.RELEASE。
项目看起来像这样
Web.xml中
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.res.context.MvcConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置文件如下所示:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.res"})
public class MvcConfig extends WebMvcConfigurerAdapter {
//I've already tried without this
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
super.configurePathMatch(configurer);
configurer.setUseRegisteredSuffixPatternMatch(false);
configurer.setUseSuffixPatternMatch(false);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// TODO Auto-generated method stub
configurer.enable();
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
jsp文件
我已经尝试了很多href值
//Those two give 404 error code
<link rel="stylesheet" href="resources/style.css" type="text/css">
<link rel="stylesheet" href="/resources/style.css" type="text/css">
//Those two give jsp fatal error with NullPointerException
<link rel="stylesheet" href='<c:uri>value="/resources/style.css"</c:uri> 'type="text/css">
<link rel="stylesheet" href='<c:uri>value="resources/style.css"</c:uri> 'type="text/css">
控制器
@Controller
@RequestMapping("/")
public class MyController {
private static final Logger logger = Logger.getLogger(MyController.class);
@RequestMapping("/site")
public ModelAndView site()
{
ModelAndView model = new ModelAndView("site");
model.addObject("txt", "Model");
return model;
}}
最后是最重要的部分
日志
2017-07-18 20:56:35 DEBUG DispatcherServlet:869 - DispatcherServlet with name 'mvc-dispatcher' processing GET request for [/res/site.htm]
2017-07-18 20:56:35 DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /site.htm
2017-07-18 20:56:35 DEBUG RequestMappingHandlerMapping:320 - Did not find handler method for [/site.htm]
2017-07-18 20:56:35 DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /site.htm
2017-07-18 20:56:35 DEBUG RequestMappingHandlerMapping:317 - Returning handler method [public org.springframework.web.servlet.ModelAndView com.res.controller.MyController.site()]
2017-07-18 20:56:35 DEBUG DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'myController'
2017-07-18 20:56:35 DEBUG DispatcherServlet:955 - Last-Modified value for [/res/site.htm] is: -1
2017-07-18 20:56:35 DEBUG DefaultListableBeanFactory:1670 - Invoking afterPropertiesSet() on bean with name 'site'
2017-07-18 20:56:35 DEBUG DispatcherServlet:1280 - Rendering view [org.springframework.web.servlet.view.JstlView: name 'site'; URL [/WEB-INF/views/site.jsp]] in DispatcherServlet with name 'mvc-dispatcher'
2017-07-18 20:56:35 DEBUG JstlView:432 - Added model object 'txt' of type [java.lang.String] to request in view with name 'site'
2017-07-18 20:56:35 DEBUG JstlView:166 - Forwarding to resource [/WEB-INF/views/site.jsp] in InternalResourceView 'site'
2017-07-18 20:56:36 DEBUG DispatcherServlet:1000 - Successfully completed request
2017-07-18 20:56:36 DEBUG DispatcherServlet:869 - DispatcherServlet with name 'mvc-dispatcher' processing GET request for [/res/resources/style.css]
2017-07-18 20:56:36 DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /resources/style.css
2017-07-18 20:56:36 DEBUG RequestMappingHandlerMapping:320 - Did not find handler method for [/resources/style.css]
2017-07-18 20:56:36 DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /resources/style.css
2017-07-18 20:56:36 DEBUG RequestMappingHandlerMapping:320 - Did not find handler method for [/resources/style.css]
2017-07-18 20:56:36 DEBUG SimpleUrlHandlerMapping:192 - Matching patterns for request [/resources/style.css] are [/resources/**]
2017-07-18 20:56:36 DEBUG SimpleUrlHandlerMapping:226 - URI Template variables for request [/resources/style.css] are {}
2017-07-18 20:56:36 DEBUG SimpleUrlHandlerMapping:140 - Mapping [/resources/style.css] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/resources/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@4c531172]]] and 1 interceptor
2017-07-18 20:56:36 DEBUG DispatcherServlet:955 - Last-Modified value for [/res/resources/style.css] is: -1
2017-07-18 20:56:36 DEBUG DispatcherServlet:1048 - Null ModelAndView returned to DispatcherServlet with name 'mvc-dispatcher': assuming HandlerAdapter completed request handling
2017-07-18 20:56:36 DEBUG DispatcherServlet:1000 - Successfully completed request
我希望有人知道这里出了什么问题,因为几个小时后我再也想不到了。
答案 0 :(得分:1)
问题是因为您拥有webapp
之外的文件夹资源,并且您的servlet将webapp
视为/
。
第一种方式:
将您的资源文件夹移至webapp
下,然后移至 applicationContext.xml ,添加下一行:
<mvc:resources mapping="/css/**" location="/resources/" />
然后您可以像这样导入style.css文件:
<link href="<c:url value="/resources/style.css" />" rel="stylesheet">
第二种方式:
您可以为静态内容创建另一个 Servlet :
首先在 web.xml
中添加下几行<servlet>
<servlet-name>resources</servlet-name>
<servlet-class>com.res.servlets.DefaultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resources</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
下一步,在该包下创建包com.res.servlet
,创建类 DefaultServlet ,如下所示:
public class DefaultServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
// Tomcat, Jetty, JBoss, and GlassFish
private static final String COMMON_DEFAULT_SERVLET_NAME = "default";
// Resin
private static final String RESIN_DEFAULT_SERVLET_NAME = "resin-file";
// WebLogic
private static final String WEBLOGIC_DEFAULT_SERVLET_NAME = "FileServlet";
// WebSphere
private static final String WEBSPHERE_DEFAULT_SERVLET_NAME = "SimpleFileServlet";
public String scanDefaultServlet(){
if(this.getServletContext().getNamedDispatcher(COMMON_DEFAULT_SERVLET_NAME) != null) {
return COMMON_DEFAULT_SERVLET_NAME;
} else if(this.getServletContext().getNamedDispatcher(RESIN_DEFAULT_SERVLET_NAME) != null) {
return RESIN_DEFAULT_SERVLET_NAME;
} else if(this.getServletContext().getNamedDispatcher(WEBLOGIC_DEFAULT_SERVLET_NAME) != null){
return WEBLOGIC_DEFAULT_SERVLET_NAME;
} else if(this.getServletContext().getNamedDispatcher(WEBSPHERE_DEFAULT_SERVLET_NAME) != null){
return WEBSPHERE_DEFAULT_SERVLET_NAME;
} else {
throw new IllegalStateException("Cannot determine what Server you currently use");
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
RequestDispatcher rd = getServletContext().getNamedDispatcher(this.scanDefaultServlet());
HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
public String getServletPath() {return "";}
};
rd.forward(wrapped, resp);
}
}
现在您可以像这样调用您的资源:
<link rel="stylesheet" type="text/css" href="<c:url value="/resources/resources/style.css"/>">
确保您已在视图顶部导入了这样的标记库:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
此致