jjzjj

java - Thymeleaf 和 Spring MVC 的表单参数为 null

coder 2024-04-01 原文

我在使用 Thymeleaf 和 Spring MVC 时遇到问题。

我正在关注 spring.io 网站上的教程 http://spring.io/guides/gs/handling-form-submission/当我尝试扩展本教程时,我遇到了一个问题。

如果我向我的模型类添加另一个参数(在我的示例中,我添加了一个 Date 参数和一个 long 参数),而不是将它们放在我的 View 中(假设这个日期参数是我的最后修改日期并且这个长参数是一个随机值),当我提交这个值时,它使我的方法中的这 2 个参数为空。

这是我的一些代码。

我的模型类

public class Greeting {

    private long id;
    private String content;
    private Date hour;
    private long longNumber;
.... getters and setters ....
}

我的 Controller

@Controller
public class GreetingController {

@RequestMapping(value="/greeting", method=RequestMethod.GET)
public String greetingForm(Model model) {

    Greeting greeting = new Greeting();
    greeting.setHour(new Date());
    greeting.setLongNumber(1234L);
    System.out.println(greeting.toString());
    model.addAttribute("greeting", greeting);
    return "greeting";
}

@RequestMapping(value="/greeting", method=RequestMethod.POST)
public String greetingSubmit(@ModelAttribute Greeting greeting, Model model) {
    System.out.println(greeting.toString());
    model.addAttribute("greeting", greeting);
    return "result";
}
}

我的表单

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handing Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
        <p>Id: <input type="text" th:field="*{id}" /></p>
        <p>Message: <input type="text" th:field="*{content}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>

结果页面

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handing Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>Result</h1>
    <p th:text="'id: ' + ${greeting.id}" />
    <p th:text="'content: ' + ${greeting.content}" />
    <p th:text="'Date: ' + ${greeting.hour}" />
    <a href="/greeting">Submit another message</a>
</body>
</html>

这是我的模型类的控制台打印

Greeting [id=0, content=null, hour=Sun Apr 26 22:29:25 GMT-03:00 2015, longNumber=1234]
Greeting [id=0, content=aaaa, hour=null, longNumber=0]

如您所见,我的两个不在我的 View 中的参数在发布后(第二行)和第一行都变为 null,它们具有值。我不明白为什么,因为我来自另一个好的框架(JSF)并且我在那里没有这样的问题。只是想知道,我正在使用 spring 4,就像在教程中一样,为什么我有一个参数不在我的 View 中?因为其中一些参数将保存一些数据,例如上次注册更新日期、上次更新注册的用户和我的应用程序 ID。

谁能帮我找到这个问题的答案?

编辑:

经过一段时间的试验,我找到了解决问题的方法。按照我的代码片段进行操作:

@Controller
@SessionAttributes({"obj"})
public class MyController {

    @RequestMapping(value = "/path", method = RequestMethod.GET)
    public ModelAndView myGet() {       
        ModelAndView modelAndView = new ModelAndView("view");
        MyClass object = new MyClass();
        modelAndView.addObject("obj", object );     
        return modelAndView;
    }

    @RequestMapping(value = "/path", method = RequestMethod.POST)
    public ModelAndView myPost(@ModelAttribute("obj") @Validated MyClass object, BindingResult result){

        ModelAndView modelAndView = new ModelAndView("view");       
        if(result.hasErrors())
            modelAndView.addObject("obj",object);
        else 
            service.save(object);
        return modelAndView;
    }   
}

最佳答案

这是预期的行为。你有 modelresponse在收到您的问候时view , 但只要 http request/response完成了,它不存在了。您将保留 <form> 中的值标记,您需要在 form 上提供这些值submit .

意思是,如果你想发回这些值,你需要添加 2 个隐藏的 input s 来保存这两个值。

<form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
    <p>Id: <input type="text" th:field="*{id}" /></p>
    <p>Message: <input type="text" th:field="*{content}" /></p>
    <input type="hidden" th:field="*{hour}" />
    <input type="hidden" th:field="*{longNumber}" />
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>

关于java - Thymeleaf 和 Spring MVC 的表单参数为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29885802/

有关java - Thymeleaf 和 Spring MVC 的表单参数为 null的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  3. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  4. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  5. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  8. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  9. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  10. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

随机推荐