简体   繁体   中英

How would i use Spring MVC to retrieve a number value from a html form?

I understand how to return a string from my controller as demonstrated here

I could modify this to take a text value from a html form.

However, when i try to retrieve number 'salary' from my form, it gives me an error of "There was an unexpected error (type=Not Found, status=404)." What needs to be fixed?

here is my ServingWebContent.java

package com.example.servingwebcontent;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServingWebContentApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServingWebContentApplication.class, args);
    }

}

here is BudgetingController.java

package com.example.servingwebcontent;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class BudgetingController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }

    @GetMapping("/results")
    public int results(@RequestParam(name="salary", required=true) int salary, Model model) {
        model.addAttribute("salary", salary);
        return salary;
    }


}

here is index.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"></html>

<head> 
    <title>Budgeting Tool</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>
    <form action="/results.html" method="GET">
        <div>
        <header>
        <h3><strong>Monthly Income</strong></h3>
        </header></div> 
    
          <div>
          <label>Monthly Salary:</label>
          <input type="number" name="salary" min="0" required>
          </div>
    
        <!--- Submits to results.html --->  
        <input type="submit" value="Submit">
    
      </form>
</body>

</html>

And finally, here is results.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Results</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text=" ${salary} " />
</body>
</html>
  1. The normal form submission method is POST.

  2. This case logic is View->Controller->View. I guess this example from https://spring.io/ . So this contact path is "/". You can change index.html and BudgetingController.java as below.

在此处输入图像描述

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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