首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >转换字符串为货币Thymeleaf

转换字符串为货币Thymeleaf
EN

Stack Overflow用户
提问于 2022-06-17 08:18:20
回答 1查看 267关注 0票数 1

我有一个问题,将输入字符串转换为货币。我正在创建一个带有晶闸管的弹簧引导应用程序。我有一个网页,用户输入数据,并且有一个特定的字段,他输入字符串,它需要转换为joda.money类型,就像在我的pojo类中,该字段有money数据类型。这是一个完整的governor_form.html:

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>[[${pageTitleG}]]</title>
    <link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}"/>
</head>
<body>
<div class="container-fluid">
    <div class="text-center"><h2>[[${pageTitleG}]]</h2></div>
    <form th:action="@{/governors/save}" method="post" th:object="${governor}" style="max-width: 550px; margin: 0 auto;">
        <input type="hidden" th:field="*{idGovernor}">
        <div class="border border-secondary rounded p-3">
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Full name:</label>
                <div class="col-sm-8">
                    <input type="text" th:field="*{fullName}" class="form-control" required minlength="5" maxlength="70">
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Age</label>
                <div class="col-sm-8">
                    <input type="number" step="0.01" th:field="*{age}" class="form-control" required>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Position</label>
                <div class="col-sm-8">
                    <input type="text" step="0.01" th:field="*{position}" class="form-control" required>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Date of Intercession</label>
                <div class="col-sm-8">
                    <input type="date" th:field="*{dateOfIntercession}" class="form-control">
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Date of Resignation</label>
                <div class="col-sm-8">
                    <input type="date" th:field="*{dateOfResignation}" class="form-control">
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Per Capita Income</label>
                <div class="col-sm-8">
                    <input type="number" step="0.01" th:field="*{perCapitaIncome}" class="form-control" required>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Population Below Poverty</label>
                <div class="col-sm-8">
                    <input type="number" step="0.01" th:field="*{populationBelowPoverty}" class="form-control" required min="0" max="99">
                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">State</label>
                <div class="col-sm-8">
                    <select th:field="*{state}" class="form-control" required>
                        <th:block th:each="state : ${listStates}">
                            <option th:text="${state.officialStateName}" th:value="${state.idState}"/>
                        </th:block>
                    </select>
                </div>
            </div>
            <div class="text-center">
                <button type="submit" class="btn btn-primary m-2">Save</button>
                <button type="button" class="btn btn-secondary m-2" onclick="cancelForm()">Cancel</button>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
    function cancelForm() {
        window.location = "[[@{/governors}]]";
    }
</script>
</body>
</html>

这就是他输入数据的地方:

代码语言:javascript
复制
<div class="form-group row">
     <label class="col-sm-4 col-form-label">Per Capita Income</label>
     <div class="col-sm-8">
          <input type="number" step="0.01" th:field="*{perCapitaIncome}" class="form-control" required>
     </div>
</div>

因此,如果我没有弄错,Hibernate就有一个问题,就是当我得到以下错误时,要将来自胸腺的字符串输入转换为输入money是个问题:

代码语言:javascript
复制
: Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'governor' on field 'perCapitaIncome': rejected value [1100]; codes [typeMismatch.governor.perCapitaIncome,typeMismatch.perCapitaIncome,typeMismatch.org.joda.money.Money,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [governor.perCapitaIncome,perCapitaIncome]; arguments []; default message [perCapitaIncome]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.joda.money.Money' for property 'perCapitaIncome'; Cannot convert value of type 'java.lang.String' to required type 'org.joda.money.Money' for property 'perCapitaIncome': no matching editors or conversion strategy found]]

这是joda.money依赖项:

代码语言:javascript
复制
<dependency>
     <groupId>org.joda</groupId>
     <artifactId>joda-money</artifactId>
     <version>1.0.1</version>
</dependency>

这是一个POJO类:

代码语言:javascript
复制
@Entity
@Table(name = "governor")
public class Governor implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_governor")
private Integer idGovernor;

@Column(name = "pib")
private String fullName;

@Column(name = "age")
private Integer age;

@Column(name = "position")
private String position;

@Column(name = "date_of_intercession")
private java.sql.Date dateOfIntercession;

@Column(name = "date_of_resignation")
private java.sql.Date dateOfResignation;

@Column(name = "per_capita_income")
private Money perCapitaIncome;

@Column(name = "population_below_poverty")
private Integer populationBelowPoverty;

@ManyToOne
@JoinColumn(name = "id_state", nullable = false)
private State state;

public State getState() {return state;}

public void setState(State state) {this.state = state;}

public Integer getIdGovernor() {
    return this.idGovernor;
}

public void setIdGovernor(Integer idGovernor) {
    this.idGovernor = idGovernor;
}

public String getFullName() {
    return this.fullName;
}

public void setFullName(String fullName) {this.fullName = fullName;}

public Integer getAge() {
    return this.age;
}

public void setAge(Integer age) {
    this.age = age;
}

public String getPosition() {
    return this.position;
}

public void setPosition(String position) {
    this.position = position;
}

public java.sql.Date getDateOfIntercession() {
    return this.dateOfIntercession;
}

public void setDateOfIntercession(java.sql.Date dateOfIntercession) {
    this.dateOfIntercession = dateOfIntercession;
}

public java.sql.Date getDateOfResignation() {
    return this.dateOfResignation;
}

public void setDateOfResignation(java.sql.Date dateOfResignation) {
    this.dateOfResignation = dateOfResignation;
}

public Money getPerCapitaIncome() {
    return this.perCapitaIncome;
}

public void setPerCapitaIncome(Money perCapitaIncome) {
    this.perCapitaIncome = perCapitaIncome;
}

public Integer getPopulationBelowPoverty() {
    return this.populationBelowPoverty;
}

public void setPopulationBelowPoverty(Integer populationBelowPoverty) {
    this.populationBelowPoverty = populationBelowPoverty;
}
}

这是一个控制器:

代码语言:javascript
复制
@Controller
public class GovernorController {
@Autowired
GovernorService governorService;

@Autowired
GovernorRepository governorRepository;

@Autowired
StateRepository stateRepository;
@Autowired
StateService stateService;

@GetMapping("/governors")
public String showAllGovernors(Model model){
    List<Governor> listGovernors = governorService.findAllGovernors();
    model.addAttribute("listGovernors", listGovernors);
    return "governors";
}

@GetMapping("/governors/new")
public String showNewGovernorForm(Model model){
    List <State>  listStates = stateService.findAll();
    model.addAttribute("listStates", listStates);
    model.addAttribute("governor", new Governor());
    model.addAttribute("pageTitleG", "Add New Governor");
    return "governor_form";
}

@PostMapping("/governors/save")
public String saveGovernor (Governor requestGovernor, RedirectAttributes redirectAttributes){
    governorRepository.save(requestGovernor);
    redirectAttributes.addFlashAttribute("messageG", "The governor has been saved successfully!");
    return "redirect:/governors";
}

@GetMapping("/governors/edit/{id}")
public String showEditGovernorForm(@PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes){
    try {
        Governor governor = governorService.findGovernorById(id);
        List <State>  listStates = stateService.findAll();
        model.addAttribute("listStates", listStates);
        model.addAttribute("governor", governor);
        model.addAttribute("pageTitleG", "Edit Governor (ID: " + id + ")");
        return "governor_form";
    } catch (EntityNotFoundException e) {
        redirectAttributes.addFlashAttribute("messageG", e.getMessage());
        return "redirect:/governors";
    }
}

@GetMapping("/governors/delete/{id}")
public String deleteGovernor(@PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes){
    try {
        governorService.deleteGovernor(id);
        redirectAttributes.addFlashAttribute("messageG", "The governor ID " + id + " has been deleted!");
    } catch (StateNotFoundException e) {
        redirectAttributes.addFlashAttribute("messageG", e.getMessage());
    }
    return "redirect:/governors";
}

}

如何将字符串转换为货币?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-17 10:31:33

一种解决方案是创建自定义的货币领域,然后使用Jackson来设置它。

下面是代码片段:

MoneyDeserializer.java :

代码语言:javascript
复制
public class MoneyDeserializer extends StdDeserializer<BigMoney> {

    private static final long serialVersionUID = 2518470236548239933L;


    public MoneyDeserializer() {
        super(Money.class);
    }

    @Override
    public BigMoney deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return BigMoney.of(CurrencyUnit.USD, jp.readValueAs(Double.class));
    }
}

Governor.java

代码语言:javascript
复制
import com.example.demo.filter.MoneyDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.joda.money.BigMoney;
import org.joda.money.Money;

import java.io.Serializable;


public class Governor implements Serializable {

    private Integer idGovernor;


    private String fullName;


    private Integer age;


    private String position;


    private java.sql.Date dateOfIntercession;


    private java.sql.Date dateOfResignation;



    private BigMoney perCapitaIncome;


    private Integer populationBelowPoverty;




    public Integer getIdGovernor() {
        return this.idGovernor;
    }

    public void setIdGovernor(Integer idGovernor) {
        this.idGovernor = idGovernor;
    }

    public String getFullName() {
        return this.fullName;
    }

    public void setFullName(String fullName) {this.fullName = fullName;}

    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPosition() {
        return this.position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public java.sql.Date getDateOfIntercession() {
        return this.dateOfIntercession;
    }

    public void setDateOfIntercession(java.sql.Date dateOfIntercession) {
        this.dateOfIntercession = dateOfIntercession;
    }

    public java.sql.Date getDateOfResignation() {
        return this.dateOfResignation;
    }

    public void setDateOfResignation(java.sql.Date dateOfResignation) {
        this.dateOfResignation = dateOfResignation;
    }

    public BigMoney getPerCapitaIncome() {
        return this.perCapitaIncome;
    }
    @JsonDeserialize(using = MoneyDeserializer.class)
    public void setPerCapitaIncome(BigMoney perCapitaIncome) {
        this.perCapitaIncome = perCapitaIncome;
    }

    public Integer getPopulationBelowPoverty() {
        return this.populationBelowPoverty;
    }

    public void setPopulationBelowPoverty(Integer populationBelowPoverty) {
        this.populationBelowPoverty = populationBelowPoverty;
    }

    @Override
    public String toString() {
        return "Governor{" +
                "idGovernor=" + idGovernor +
                ", fullName='" + fullName + '\'' +
                ", age=" + age +
                ", position='" + position + '\'' +
                ", dateOfIntercession=" + dateOfIntercession +
                ", dateOfResignation=" + dateOfResignation +
                ", perCapitaIncome=" + perCapitaIncome +
                ", populationBelowPoverty=" + populationBelowPoverty +
                '}';
    }
}

注意:表单上的age字段作为Double传递,但是在您的类中它被声明为Integer。因此,你会得到例外,在当兵过程中。同样的东西也适用于populationBelowPoverty字段。另外,您的日期格式是dd/MM/YYYY,我认为杰克逊不支持这种格式。应该是YYYY-MM-dd

无论如何,例如,如果您发送这样的JSON:

代码语言:javascript
复制
{
     "idGovernor":1,
     "fullName":"Test",
     "age":1,
     "dateOfIntercession":"2022-06-09",
     "dateOfResignation":"2022-06-17",
     "perCapitaIncome":"123.932",
     "position":"position",
     "populationBelowPoverty":"98"
}

对于此控制器方法:

代码语言:javascript
复制
@PostMapping(value = "/test/governor")
    public Governor testGovernor(@RequestBody Governor governor)  {
        return governor;

    }

你应该得到这样的回应:

代码语言:javascript
复制
{
    "idGovernor": 1,
    "fullName": "Test",
    "age": 1,
    "position": "position",
    "dateOfIntercession": "2022-06-09",
    "dateOfResignation": "2022-06-17",
    "perCapitaIncome": {
        "amount": 123.932,
        "zero": false,
        "negative": false,
        "positive": true,
        "amountMajorLong": 123,
        "negativeOrZero": false,
        "amountMinorLong": 12393,
        "amountMinor": 12393,
        "positiveOrZero": true,
        "minorPart": 93,
        "scale": 3,
        "amountMinorInt": 12393,
        "currencyUnit": {
            "code": "USD",
            "numericCode": 840,
            "decimalPlaces": 2,
            "symbol": "$",
            "numeric3Code": "840",
            "countryCodes": [
                "PR",
                "MP",
                "IO",
                "FM",
                "PW",
                "GU",
                "BQ",
                "TC",
                "VG",
                "AS",
                "VI",
                "TL",
                "UM",
                "MH",
                "EC",
                "US"
            ],
            "pseudoCurrency": false
        },
        "currencyScale": false,
        "amountMajorInt": 123,
        "amountMajor": 123
    },
    "populationBelowPoverty": 98
}

在你的情况下,因为你正在使用胸腺细胞,你可以调整这个想法,以满足你的需要。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72656334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档