简体   繁体   English

弹簧和速度-表格处理

[英]Spring and Velocity - form handling

I googled it, but could not find completely full answer. 我用谷歌搜索,但找不到完全完整的答案。 How can I handle the form from Spring, if I use Velocity templates as View? 如果我将Velocity模板用作View,如何从Spring处理表单? Assume I have the following form: 假设我具有以下形式:

<form action="" method="POST" id="newThreadForm">
    <input type="text" placeholder="Title" id="title"/>
    <input type="text" placeholder="Author" id="author"/>
    <input type="text" placeholder="E-mail" id="email">
    <!-- other fields... -->
</form>

And have a simple class: 并有一个简单的类:

public class Post {
    private int id;
    private String author;
    private String email;
    private String title;
    //other fields

    //getters and setters
}

How can I convert the data that user types in the form to Post object in my Controller method? 如何在Controller方法中将用户在表单中键入的数据转换为Post对象?

 @RequestMapping(value="path/to/", method=RequestMethod.POST)
 public String newThread(Model model) {
     //what should be there?
     return "view-name"; 
 }

Do I need to create a new class, smth like public class NewThreadForm ? 我是否需要创建一个新类,例如public class NewThreadForm Add BindingResult argument to the method? 将BindingResult参数添加到方法? Or what should I do? 或者我该怎么办? Thanks for answers. 感谢您的回答。

UPD: I wrote: UPD:我写道:

@RequestMapping(value="/{board}/new", method=RequestMethod.POST)
public String newThread(Model model, @PathVariable("board") String boardName, Post post, HttpServletRequest request) {
    log.info("newThread()");
    Board board = new Board();
    board.setName(boardName);
    post.setBoard(board);
    post.setDeletePassword(DigestUtils.md5DigestAsHex(post.getDeletePassword().getBytes()));
    post.setIp(request.getRemoteAddr());
    Thread newThread = new Thread();
    newThread.setOpPost(post);
    threadDao.addThread(newThread);
    return "redirect:/" + boardName; 
}

But when I send the form data, Spring shows me 400 error: The request sent by the client was syntactically incorrect. 但是,当我发送表单数据时,Spring向我显示400错误:客户端发送的请求在语法上不正确。 First line log.info("newThread()"); 第一行log.info("newThread()"); doesn't runs. 不运行。 What's wrong? 怎么了?

UPD2: it was cause of "id", not "name" attributes in form html UPD2:这是表单html中的“ id”属性而非“ name”属性的原因

public String newThread(Post post, Model model) { ... } should work. public String newThread(Post post, Model model) { ... }应该可以工作。 You will get a populated Post instance inside the method that you can validate, persist, etc. 您将在可以验证,保留等的方法内获得一个填充的Post实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM