【问题标题】:Form created with Thymeleaf returns null object使用 Thymeleaf 创建的表单返回空对象
【发布时间】:2015-10-05 19:09:13
【问题描述】:

我已经学习了所有的教程,但是我仍然有一个问题,我无法使用 Spring MVC 将对象从表单获取到控制器。可能是什么情况?我正在使用 Thymeleaf 来格式化我的 jsp 页面。

这里是风景

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="" th:action="@{/increaseprice}" th:object="${priceIncrease}" method="post">
    <input type="text" th:field="*{message}" />
  <p><input type="submit" value="Submit" />
</form>
</body>
</html>

控制器

package com.springapp.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import store.service.PriceIncrease;

import org.apache.commons.logging.*;

@Controller
public class PriceIncreaseFormController{

    protected final Log logger = LogFactory.getLog(getClass());

    @RequestMapping(value="/increaseprice.html", method = RequestMethod.POST)
    public String increasePrice(@ModelAttribute("priceIncrease") PriceIncrease priceIncrease){
        int increase = priceIncrease.getPercentage();
        logger.info("Percentage " + increase);
        logger.info("Message " + priceIncrease.getMessage());
        return "priceincrease";
    }

    @RequestMapping(value="increaseprice.html", method = RequestMethod.GET)
    public String showIncreasePrice(Model model){
        PriceIncrease priceIncrease = new PriceIncrease("testmessage");
        model.addAttribute("priceIncrease", priceIncrease);

        return "priceincrease";
    }
}

Java 类

package store.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PriceIncrease {
    protected final Log logger = LogFactory.getLog(getClass());

    private int percentage;
    private String message;

    public PriceIncrease(){

    }

    public PriceIncrease(String message){
        this.message = message;
    }

    public void setPercentage(int i){
        percentage = i;
        logger.info("Percentage set to " + i);
    }

    public int getPercentage(){
        return  percentage;
    }

    public String getMessage(){
        return this.message;
    }

    public void setMessage( String message ){
        this.message = message;
    }
}

【问题讨论】:

    标签: java spring forms model-view-controller thymeleaf


    【解决方案1】:

    我相信您不需要 @ModelAttribute,因为 Spring MVC 足够聪明,可以将表单映射到您的 PriceIncrease 控制器参数。

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 2014-07-07
      • 2019-10-06
      • 2023-01-01
      • 2021-12-31
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多