Sping MVC在路径中缺少应用程序上下文



简而言之,我遇到的问题是,当我打开应用程序时http://localhost:8080/[应用程序上下文]/一切正常。但是当我按下一个链接"/另一页";,我得到一个404错误,URL是http://localhost:8080/otherpage.如果我手动书写http://localhost:8080/[应用程序上下文]/otherpage,然后我被重定向到正确的页面。

我将Spring MVC与Tomcat-9一起使用。其使用在应用程序上下文设置为"0"的情况下爆发的战争/[应用上下文]";

我的控制器

@RequestMapping(value = "/")
@Controller
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String printHallo(ModelMap model){
return "hello";
}
@RequestMapping("/otherpage")
public String printHallo(ModelMap model){
return "otherpage";
}
}

JSP文件hello

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html charset=utf-8"%>
<html>
<%@ include file="common/header.jspf"%>
<body>
<form:form action="/otherpage">
<input type="submit" value = "otherpage">
</form:form>
</body>
</html>

Web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Servlet

<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-3.0.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-3.0.xsd">
<context:component-scan base-package="knox.frontend"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/"
cache-period="31556926"/>
<mvc:annotation-driven />
</beans>

我读了好几篇文章。但还不知道该怎么办。这似乎与Tomcat的配置有关。

我找到了一些解决方案,但它们感觉不是正确的做法。但我是春天的新手,所以我可能错了。

如果我链接到";其他页面";而不是"/另一页";,然后它就起作用了,但我还是不能肯定"进入主页。

如果我将应用程序上下文更改为仅"/&";,然后一切都很好,但这似乎是一个解决方案,可能会让我头疼。因为感觉我只是在回避这个问题。

我在一篇文章中也读到,你应该在链接前面添加${pageContext.servletContext.contextPath}。这也起作用,但只在JSP文件中起作用。它看起来像是某种东西,应该可以自动添加。

所以我的问题是,当涉及到客户端的链接时,处理应用程序上下文的正确方式是什么。

一个简短的答案是Spring MVC是如何工作的,您需要将其放入jsp文件中:

<form:form action="HelloWeb/otherpage">

最新更新