【问题标题】:Spring MVC open index.jsp on "/"Spring MVC 在“/”上打开 index.jsp
【发布时间】:2014-05-09 20:31:38
【问题描述】:

如何使用这个 url http://localhost:8080/myApp/打开 index.jsp 以及如何使用这样的超链接 <a href="/">HOME</a> 并转到 index.jsp (http://localhost:8080/myApp/)?

这是我的 web.xml:

<display-name>myApp</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/application-config.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>myApp</servlet-name>
    <servlet-class>
       org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>myApp</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

这是我的 myApp-servlet.xml:

<context:component-scan base-package="org.myApp.com" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

提前致谢!

【问题讨论】:

    标签: java spring jsp spring-mvc servlets


    【解决方案1】:

    只需使用适当的处理方法添加@Controller

    @Controller
    public class RootController {
        @RequestMapping(value = "/", method = RequestMethod.GET)
        public String root() {
            return "index";
        }
    }
    

    假设index.jsp 在/WEB-INF/view 中。

    【讨论】:

    • 如果在 url localhost:8080/myApp 中放入但不在超链接上,它可以工作
    • @user3476247 在超链接中,单个/ 表示相对于主机的绝对路径。这意味着它将执行localhost:8080/,而不是localhost:8080/myapp。您需要使用${pageContext.request.contextPath} 直接或动态提供上下文路径。
    • 问题已解决。但是现在你让我想知道为什么我的 ABOUT 元素不需要上下文路径:D
    • @user3476247 因为前面没有/。因此,当浏览器生成将请求发送到的路径时,它会将该值视为相对于您当前的 URL,并用您的值替换最后一个路径元素。所以href="somepath/more"当你在localhost:8080/myapp/users/admins时,浏览器会将请求发送到localhost:8080/myapp/users/somepath/more。
    猜你喜欢
    • 2015-09-08
    • 2014-10-27
    • 2021-07-09
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    相关资源
    最近更新 更多