簡體   English   中英

由於錯誤的InternalResourceViewResolver視圖名稱,Spring MVC返回404

[英]Spring MVC returns a 404 because of a wrong InternalResourceViewResolver view name

我是Spring MVC和Boot的新手。 我可以打開http:// localhost:8088 / postList,但是打開http:// localhost:8088 / post / 1時遇到Whitelabel Error Page錯誤。 我找不到我的錯誤。 你能說嗎

我的項目結構

在此處輸入圖片說明

我的InternalResourceViewer:

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

簡短的答案是,您在InternalResourceViewResolver前綴中需要一個前導/ 所以

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

長的答案是Spring MVC使用InternalResourceViewResolver生成一個View ,在這種情況下為JstlView 然后,Spring MVC嘗試渲染此View

要做到這一點,它使用的視圖名稱(前綴,在你的名字ModelView ,和后綴,即WEB-INF/views/post.jsp ),作為路徑,並嘗試獲取一個RequestDispatcher通過委派到ServletRequest#getRequestDispatcher(String)

指定的路徑名​​可以是相對的 ,盡管它不能擴展到當前servlet上下文之外。 如果路徑以"/"開頭,則將其解釋為相對於當前上下文根。 如果Servlet容器無法返回RequestDispatcher則此方法返回null

由於您沒有前導/ ,所以它相對於當前路徑,即。 /post/1 這使其成為/post/WEB-INF/views/post.jsp 並且由於沒有相對於ServletContext資源,因此Servlet容器返回404。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM