Spring MVC主页

时间:2017-07-05 18:19:09

标签: java spring jsp spring-mvc

我有HomeController类:

@Controller
public class HomeController {

    @RequestMapping("/")
    public String showPage() {
        return "main-menu";
    }
}

我的项目结构: enter image description here

春季版:4.3.9 web.xml中:

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>

调度-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

它总是显示index.jsp,而不是main-menu.jsp 我想要一个主菜单我的主页。我该怎么办?

2 个答案:

答案 0 :(得分:1)

我在项目中使用了一种方法来解决这个问题。 我将在下面与您分享

仅保留index.jsp

中的内容
index.jsp

<meta http-equiv="refresh" content="0;url=welcome" />

在您的控制器java程序中,RequestMapping必须包含url文件中指定的<meta>标记的index.jsp属性中指定的值。

在此示例中,url属性的值为welcome

@Controller
public class HomeController {

    @RequestMapping("/welcome")
    public String welcome() {
        return "main-menu";
    }
}

这对我有用

更新了#1:

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

更新了#2:

<context:annotation-config />
<context:component-scan base-package="add your base folder here" />

答案 1 :(得分:1)

问题在于您的web.xml文件:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.form</url-pattern>
</servlet-mapping>

您向servlet容器声明SpringMVC DispatcherServlet将仅处理以.form结尾的URL。所以对家庭的要求永远不会到达SpringMVC机器 - BTW,这也解释了为什么神的/welcome的提议也不起作用,但是/welcome.form应该......

您还可以查看我的其他post,了解如何使用SpringMVC处理根URL。