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

14ifxucb  于 2023-05-06  发布在  Eclipse
关注(0)|答案(2)|浏览(135)

我在eclipse中有以下Spring项目:

当我去:

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>
2g32fytz

2g32fytz1#

步骤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"; 
    }   
}
nom7f22z

nom7f22z2#

简单地说,您的Web应用程序将查看welcome page,并调用/redirect,这是由controller类捕获的,并执行您实现的逻辑。
web.xml中添加此内容

<welcome-file-list>
        <welcome-file>hello.jsp</welcome-file>
    </welcome-file-list>

JSP本身中,添加以下编码:

<c:redirect url="/directMe"/>

最后,在控制器中:

@RequestMapping(value = "/directMe", method = RequestMethod.GET)
        public void myMethod(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException { 
// add your logic to execute
}

相关问题