【问题标题】:Spring MVC returns a 404 because of a wrong InternalResourceViewResolver view name由于 InternalResourceViewResolver 视图名称错误,Spring MVC 返回 404
【发布时间】:2017-05-08 04:50:04
【问题描述】:

我是 Spring MVC 和 Boot 的新手。我可以打开 http://localhost:8088/postList 但在打开 http://localhost:8088/post/1 时遇到 Whitelabel Error Page 错误。我找不到我的错误。可以说吗?

我的项目结构

我的内部资源查看器:

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

我的控制器:

@Controller
@RequestMapping("/")
public class PostController 
{

@Autowired
PostService postService;

@RequestMapping(value="/post/{id}", method=RequestMethod.GET)
public ModelAndView list(@PathVariable("id") int id){

    ModelAndView mav=new ModelAndView("post");

    Post postItem=postService.getPostById(id);
    mav.addObject("postItem",postItem);

    mav.addObject("postItem",postItem);

    return mav;
}

@RequestMapping(value="/postList", method=RequestMethod.GET)
public ModelAndView postlist(){

    ModelAndView mav=new ModelAndView("postList");
    mav.addObject("postList",postService.listPosts());

    return mav;
}


}

我的帖子列表:

我的帖子查看页面:

我的 postList.jsp 标签库和内容:

    <div class="row">

      <c:if test="${not empty postList}">
          <c:forEach var="postItem" items="${postList}">
              <div class="col-lg-8">

                  <h1><a href="<c:url value='/post/${postItem.id}' />">${postItem.header}</a></h1>

                  <p class="lead">
                      by <a href="#">${postItem.user_id}</a>
                  </p>

                  <p><span class="glyphicon glyphicon-time"></span>${postItem.upddate}</p>

                   <hr>
              </div>
          </c:forEach>
        </c:if>

【问题讨论】:

  • 向我们展示带有链接的postList.jsp 内容。

标签: java jsp spring-mvc http-status-code-404


【解决方案1】:

简短的回答是,您需要在 InternalResourceViewResolver 前缀中使用前导 /。所以

resolver.setPrefix("/WEB-INF/views/");

长答案是 Spring MVC 使用InternalResourceViewResolver 生成View,在本例中为JstlView。 Spring MVC 然后尝试渲染这个View

为此,它使用视图名称(前缀、ModelView 中的名称和后缀,即WEB-INF/views/post.jsp)作为路径,并尝试通过委托给@ 来检索RequestDispatcher 987654323@.

指定的路径名​​可能是相对的,虽然它不能扩展 在当前 servlet 上下文之外。 如果路径以"/" 开头 被解释为相对于当前上下文根。此方法 如果 servlet 容器不能返回 null RequestDispatcher.

由于您没有前导/,因此它是相对于当前路径的,即。 /post/1。这使它成为/post/WEB-INF/views/post.jsp。而且由于您没有相对于 ServletContext 的此类资源,因此您的 Servlet 容器返回 404。

【讨论】:

  • 我多么想念它。非常感谢 Sotirios。当我添加到前缀的“/”头时,它就解决了。
猜你喜欢
  • 2022-10-17
  • 2018-12-08
  • 1970-01-01
  • 2019-10-22
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多