Spring MVC open index.jsp on “/”

2019-08-08 18:28发布

问题:

How can I open index.jsp using this url http://localhost:8080/myApp/and how can I use an hyperlink like this <a href="/">HOME</a> and go to index.jsp (http://localhost:8080/myApp/)?

Here's my 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>

And here is my 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>

Thanks in advance!

回答1:

Just add a @Controller with an appropriate handler method

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

assuming index.jsp is in /WEB-INF/view.