将对象从视图传递到控制器

时间:2018-12-24 12:49:12

标签: spring-mvc jsp controller

我想通过控制器从.jsp输入向数据库添加新消息。我试图只是在控制器中创建消息的新对象,并将其放入数据库中,并且工作正常。但是当我尝试使用输入来执行此操作时,会收到如下错误:

SEVERE [http-nio-8080-exec-2]org.springframework.web.servlet.tags.form.InputTag.doStartTag Neither   BindingResult nor plain target object for bean name 'message' available as  request attribute
 java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'message' available as request attribute

我的代码:

@Controller
public class DemoController {

@Autowired
UserService userService;

@Autowired
MessageService messageService;

@PostMapping("/messages/sendNewMessage")
public String sendNewMessage(@ModelAttribute("message") MessagesEntity tempMessage) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    tempMessage.setFromUsername(userService.getUser(auth.getName()));

    messageService.sendNewMessage(tempMessage);
    return "redirect:/messages";
}
}

JSP在这里

<form:form action="sendNewMessage" modelAttribute="message" method="POST">

    <table>
        <tbody>
        <tr>
            <td><label>Username:</label></td>
            <td><form:input path="toUsername" /></td>
        </tr>

        <tr>
            <td><label>Subject:</label></td>
            <td><form:input path="subject" /></td>
        </tr>

        <tr>
            <td><label>Content:</label></td>
            <td><form:input path="content" /></td>
        </tr>

        <tr>
            <td><label></label></td>
            <td><input type="submit" value="Send" class="save" /></td>
        </tr>


        </tbody>
    </table>
</form:form>

2 个答案:

答案 0 :(得分:0)

您在jsp视图中将动作URL用作#include <string> string getParentDirectory(string& filePath) { if (filePath.empty() == false) { size_t toPos = filePath.find_last_of('\\') - 1; if (toPos != string::npos) { size_t fromPos = filePath.find_last_of('\\', toPos); if (fromPos != string::npos) { return filePath.substr(fromPos + 1, toPos - fromPos); } } } return ""; } int main() { string str = "D:\\Devs\\Test\\sprite.png"; string parentDir = getParentDirectory(str); return 0; } ,但在控制器中,它是sendNewMessage

答案 1 :(得分:0)

您需要将MessagesEntity对象放入ModelAttribute中。

在加载如下所示的表单页面时,定义ModelAttribute。

@RequestMapping(value = "/", method = RequestMethod.GET) 
public String messageForm(Model model) { 
    model.addAttribute("message", new MessagesEntity()); 
    return "messageFormPageName"; 
}

或在控制器中放置以下方法,这对于完整的控制器来说是通用的,因此ModelAttribute将始终可用。

@ModelAttribute("message")
public MessagesEntity createModel() {
    return new MessagesEntity();
}