尝试获取CSS文件时出现“请求方法GET不支持”错误

时间:2015-08-02 00:47:07

标签: java html css jsp spring-mvc

我有一个JSP文件,其中包含<head>中CSS​​的链接。但是,当我点击该链接时,我收到HTTP ERROR 405: Request method 'GET' not supported

的index.jsp:

<head>
   <title>The Ultimate Address App</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <link href="${pageContext.servletContext.contextPath}/resources/css/bootstrap.css" rel="stylesheet" type="text/css">
</head>

这是我的目录结构。

webapp
   resources
      css
         bootstrap.css
   WEB-INF
      views
         jsp
            index.jsp

Config.java:

@EnableWebMvc
@Configuration
@ComponentScan({ "com.bpd.addressapp.controllers" })
public class Config extends WebMvcConfigurerAdapter {

   private static final Logger LOGGER = Logger.getGlobal();

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
   }

   @Bean
   public InternalResourceViewResolver viewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setViewClass(JstlView.class);
      viewResolver.setPrefix("/WEB-INF/views/jsp/");
      viewResolver.setSuffix(".jsp");
      return viewResolver;
   }

}

我没有使用任何XML配置文件,因此这里是web.xml文件的Java版本。

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return Arrays.asList(Config.class).toArray(new Class[1]);
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return null;
   }

   @Override
   protected String[] getServletMappings() {
     return Arrays.asList("/").toArray(new String[1]);
   }

}

在我的控制器中,我有这个方法:

@Controller
public class MainController {

   @RequestMapping(value = "/", method = RequestMethod.GET)
   public String index(Map<String, Object> model) {
      ...
      return "index";
   }

   ...

}

我怀疑控制器导致了这个问题。当我删除value = "/"然后点击HTML源代码中CSS文件的链接时,我被重定向回index.jsp页面。

如何解决此问题,以便正确呈现index.jsp页面?

1 个答案:

答案 0 :(得分:0)

尝试使用:

<link href="<c:url value="/resources/css/bootstrap.css"/>" rel="stylesheet" type="text/css">

并且不要忘记在jsp文件的顶部包含taglib:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>