控制器在Spring MVC中被调用了3次

时间:2014-10-23 18:08:37

标签: java spring spring-mvc

我在我的项目中简化了我的代码,只留下了web.xml,webcontext配置和最简单的控制器与调用计数器,但问题仍然存在

结果我有一个接一个的3个电话,为什么?

Web.xml中

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Spring MVC Application</display-name>
    <welcome-file-list>
        <welcome-file>main.jsp</welcome-file>

    </welcome-file-list>

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

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

WebContext

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <context:component-scan base-package="com.dubovskiy.movc"/>
    <mvc:annotation-driven />
    <context:annotation-config/>

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

</beans>

控制器

@Controller
public class HelloController {
    public static int count;

    @RequestMapping(value = {"/", "/main"}, method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {

        model.addAttribute("M"," Have many times "+ ++count);
        return "main";
    }
}

查看

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>

</head>
<body>

<h2>${M}</h2>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我有一个空的href用于css导入,一个空的src用于javascript导入。真糟糕!

但奇怪的是,这会导致重复调用控制器 - 在我的情况下最多六次。

请参阅完整的答案

http://forum.spring.io/forum/spring-projects/web/46115-controller-called-twice-in-one-request-when-changed-the-view