例如,如果您的 Web 应用程序存在于 Web 服务器的 webapps 目录中,webapps/myapp/
则可以在http://localhost:8080/myapp/
假定默认 Tomcat 端口时访问此应用程序上下文的根目录。我认为默认情况下,这应该使用或不使用斜杠- 当然在 Jetty v8.1.5 中就是这种情况
一旦您点击/myapp
Spring DispatcherServlet接管,将请求路由到您的<servlet-name>
配置web.xml
,在您的情况下是/ui/*
.
然后 DispatcherServlet 将所有请求路由http://localhost/myapp/ui/
到@Controller
s。
在控制器本身中,您可以使用@RequestMapping(value = "/*")
mainPage ()方法,这将导致两者都http://localhost/myapp/ui/
被http://localhost/myapp/ui
路由到mainPage()。
注意:由于SPR-7064,您还应该使用 Spring >= v3.0.3
为了完整起见,以下是我测试过的文件:
src/main/java/controllers/UIRootController.java
package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UiRootController {
@RequestMapping(value = "/*")
public ModelAndView mainPage() {
return new ModelAndView("index");
}
@RequestMapping(value={"/other"})
public ModelAndView otherPage() {
return new ModelAndView("other");
}
}
WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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" metadata-complete="false">
<servlet>
<servlet-name>ui</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<!-- spring automatically discovers /WEB-INF/<servlet-name>-servlet.xml -->
</servlet>
<servlet-mapping>
<servlet-name>ui</servlet-name>
<url-pattern>/ui/*</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/ui-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="controllers" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="2"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp"/>
</beans>
还有 2 个 JSP 文件位于WEB-INF/views/index.jsp
和WEB-INF/views/other.jsp
.
结果:
http://localhost/myapp/
-> 目录列表
http://localhost/myapp/ui
和http://localhost/myapp/ui/
-> index.jsp
http://localhost/myapp/ui/other
和http://localhost/myapp/ui/other/
-> other.jsp
希望这可以帮助!