【问题标题】:Spring 3 Controllers - Maintaining Model Through FlowSpring 3 控制器 - 通过流维护模型
【发布时间】:2010-06-10 13:07:20
【问题描述】:

我确信这里有一些方法可以完成我想要的,但我无法在文档中找到它

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/test")
public class TestController {

    @RequestMapping(value = "/one")
    public String one(Model m) {
        System.out.println("one: m = " + m);
        m.addAttribute("one", "valueone");
        return "redirect:two";
    }

    @RequestMapping(value = "/two")
    public String two(Model m) {
        System.out.println("two: m = " + m);
        return "redirect:three";
    }

    @RequestMapping(value = "/three")
    public String three(Model m) {
        System.out.println("three: m = " + m);
        return "redirect:one/two/three";
    }

    @RequestMapping(value = "/one/two/three")
    public String dest(Model m) {
        System.out.println("one/two/three: m = " + m);
        return "test";
    }
}

我在这里期望看到值为“valueone”的模型属性“one”应该出现在方法调用 two()、three() 和 dest() 中,但是它非常显眼缺席。我将如何使这项工作按预期进行?

【问题讨论】:

    标签: java model spring-mvc controller


    【解决方案1】:

    您需要在控制器上使用@SessionAttributes 注解,然后使用 SessionStatus 告诉框架您何时完成了该属性。

    @Controller
    @RequestMapping(value = "/test")
    @SessionAttributes("one")
    public class TestController {
        // ...
    
        @RequestMapping(value = "/one/two/three")
        public String dest(Model m, SessionStatus status) {
            System.out.println("one/two/three: m = " + m);
            status.setComplete();
            return "test";
        }
    }
    

    http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/SessionAttributes.html

    【讨论】:

    • 太棒了,太棒了,我已经阅读了SessionAttributes文档,但是直到现在我才明白。唯一让我担心的是它似乎至少通过查询字符串将字符串值放入 url,但是当我用对象测试它时效果很好,并且根本不修改查询字符串,你认为这是一个错误?
    • 我从来没有用它来存储字符串属性,所以我没有注意到这种行为。我想暴露这些属性可能是一个错误,尽管可能有一个旋钮可以在某个地方旋转来设置它。我无法立即看到这可能在哪里,不确定哪个类实际处理 SessionAttributes 属性存储。无论如何,您都有解决方法。
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2015-05-04
    相关资源
    最近更新 更多