【发布时间】:2021-02-05 13:13:44
【问题描述】:
简而言之,我遇到的问题是,当我打开应用程序 http://localhost:8080/[Application-Context]/ 时,一切正常。但是当我按下链接“/otherpage”时,我得到一个 404 错误,并且 URL 是 http://localhost:8080/otherpage。如果我手动编写 http://localhost:8080/[Application-Context]/otherpage 那么我会被重定向到正确的页面。
我将 Spring MVC 与 Tomcat-9 一起使用。 它使用了一个将应用程序上下文设置为“/[Application-Context]”的战争爆发
我的控制器
@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 文件你好
<%@ 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>
小服务程序
<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的配置有关。
我找到了一些解决方案,但它们感觉不是正确的做法。但我是 Spring 新手,所以我可能错了。
如果我链接到“其他页面”而不是“/其他页面”,那么它可以工作,但我仍然无法通过“/”进入主页。
如果我将应用程序上下文更改为“/”,那么一切正常,但这似乎是一个可能让我头疼的解决方案。感觉就像我只是在回避这个问题。
我还在一篇文章中读到,您应该在链接前添加 ${pageContext.servletContext.contextPath}。这也有效,但这只适用于 JSP 文件。看起来,应该可以自动添加。
所以我的问题是,当涉及到客户端的链接时,处理应用程序上下文的正确方法是什么。
【问题讨论】:
标签: java spring spring-mvc tomcat http-status-code-404