在jsp中,单击类别后,它会动态添加到bookRecommendation路径的末尾,因此您会获得/ bookRecommendation / fiction或/ bookRecommendation / biography等。

问题:这样做之后,当我单击另一个链接时,它只是被附加到路径中,因此当我只希望它带我到/ aboutMe时,请选择bookRecommendation / aboutMe。在将包含path变量的方法添加到控制器之前,一切都按预期工作。

@Controller
public class SiteController {

@RequestMapping(path="/bookRecommendations/{category}", method=RequestMethod.GET)
public String displayCategoryPage(@PathVariable String category, ModelMap model) {
    List<Book> bookList = new ArrayList<>();
    bookList = bookDAO.getBooksByCategory(category);
    model.put("category", category);
    model.put("books", bookList);
    return "bookCategoryTemplate";
}

@RequestMapping("/aboutMe")
public String displayAboutMe() {
    return "aboutMe";
}
}


bookRecommendations.jsp:

    <div class="row">
        <div class="col-md-12">
            <div class="dropdown">
                <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Go To...
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <c:forEach items="${categories}" var="category">
                        <li><a href="bookRecommendations/${category.name}">${category.name}</a></li>
                    </c:forEach>
                </ul>
            </div>
        </div>
    </div>


bookCategoryTemplate.jsp:

<div class="book-category-template">
    <h1 class="book-category-header">${category}</h1>
    <c:forEach items="${books}" var="book">
        <h3>${book.title}</h3>
    </c:forEach>
</div>


header.jsp

<header class="navbar navbar-default">
    <div class="container">
        <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav">
                <li><a href="bookRecommendations">Book Recommendations</a></li>
                <li><a href="aboutMe">About Me</a></li>
                <li><a href="login">Login</a>
            </ul>
        </div>
    </div>
</header>


viewResolver.xml,如果有帮助的话:

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>


有任何想法吗?谢谢!

最佳答案

controller没有任何问题。您使用的是relative路径。您需要在服务器上使用absolute路径:

<a href="bookRecommendations/${category.name}">${category.name}</a>


改成这个

<a href="/bookRecommendations/${category.name}">${category.name}</a>

07-27 13:47