设置Spring MVC Web应用程序的起始页面?

时间:2016-05-07 14:21:29

标签: eclipse jsp spring-mvc

我在eclipse中有以下Spring项目:

enter image description here

当我去:

http://[my-host]:8082/webapp-module/hello

WEB / INF / jsp / hello.jsp 页面加载得很好。但是当我去的时候,我还想定义一个默认的起始页面(WEB / INF / index.jsp):

http://[my-host]:8082/webapp-module

目前这不起作用。我需要为此添加单独的控制器吗?

我的 web.xml 文件:

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>

    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/webapp-module-servlet.xml</param-value>
    </context-param>

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

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

   <servlet-mapping>
      <servlet-name>webapp-module</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

我的 webapp-module-servlet.xml 文件:

<beans xmlns="http://www.springframework.org/schema/beans"
   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/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

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

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

</beans>

1 个答案:

答案 0 :(得分:2)

步骤1:将index.jsp移到/WEB-INF/jsp/文件夹中。

第2步:在@Controller课程中添加以下方法:

@RequestMapping("/") 
public String home(){
    return "index"; 
} 

您的完整Controller类应如下所示:

@Controller 
public class LoginController { 

    @RequestMapping("/") 
    public String home(){
        return "index"; 
    }  

    @RequestMapping("/hello") 
    public String showhello(){
        return "hello"; 
    }   
}