【问题标题】:The requested resource is not available error in Spring Web MVCSpring Web MVC 中请求的资源不可用错误
【发布时间】:2017-02-14 09:11:55
【问题描述】:

亲爱的利他主义者,

我正在尝试运行 Spring Web MVC HelloWeb 项目,但它总是显示“请求的资源不可用”错误。 你能帮我解决这个问题吗?

项目结构:

web.xml 文件:

HelloWeb-servlet.xml 文件:

HelloController.java 文件:

【问题讨论】:

  • 你在localhost:8080 获取tomcat/other 主页吗?有时eclipse不会给你tomcat webapps。
  • 是的,“localhost:8080”正在正确显示 Tomcat 主页...
  • “运行项目”是指“在服务器上运行”选项?浏览器中还显示什么 URL?启动tomcat后,当你转到`localhost:8080/HelloWeb/hello'时会发生什么。 ?
  • 您使用的是动态网络项目吗?类路径中是否存在所有库?我认为您应该使用 maven 或 gradle 来构建项目。
  • helloweb-servlet 中添加<mvc:annotation-config/> 就可以了

标签: spring spring-mvc spring-boot spring-security tomcat7


【解决方案1】:

根据错误消息,您似乎没有在 Tomcat 中定义上下文。

在 META-INF 文件夹中包含一个名为 context.xml 的文件,其内容为:

<?xml version="1.0" encoding="UTF-8"?>

<Context path="/HelloWeb"/>

来自 tomcat 文档:

Tomcat Context Container Documentation

可以明确定义各个上下文元素:

在应用程序内 /META-INF/context.xml 的单个文件中 文件。可选(基于主机的 copyXML 属性)这可能是 复制到 $CATALINA_BASE/conf/[enginename]/[hostname]/ 并重命名为 应用程序的基本文件名加上“.xml”扩展名。

另外,返回一个 ModelView 对象而不是一个字符串以重定向到您的 home.jsp 页面。

@RequestMapping(method = RequestMethod.GET)
protected ModelAndView printHello(HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    ModelAndView model = new ModelAndView("hello");

    return model;
}

【讨论】:

  • 我已将 context.xml 文件包含到 META-INF 文件夹中,但仍然出现同样的错误。
  • printHello的实现是正确的。无需将其更改为ModelAndView 模式。它返回的字符串"hello" 不仅仅是一个字符串。这是一个视图名称。这里它指向hello.jsp。但我不知道是什么导致了这个问题。
  • 我已经实现了 ModelAndView 模式,但仍然是同样的问题。 @alfcope
【解决方案2】:

像这样替换你的 beans 标签。

 <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">

【讨论】:

  • 已应用,但还是同样的错误...@Controller public class HelloController{ @RequestMapping(value = "/hello", method = RequestMethod.GET) public ModelAndView printHello(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("hello"); return model; } }
  • 尝试在 helloweb-servlet 中添加
  • 显示编译错误:元素“mvc:annotation-config”的前缀“mvc”未绑定。 @jagga
  • 查看编辑后的答案。替换 helloweb-servlet 中的代码
  • 我已经用你的标签替换了我的 helloweb-servet.xml,之后它在 Eclipse 中显示了另一个编译错误。 "cvc-complex-type.2.4.c: 匹配通配符是严格的,但是找不到元素'mvc:annotation-config'的声明。"
猜你喜欢
  • 2018-03-06
  • 2013-02-16
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多