繁体   English   中英

Spring:将值作为对象形式映射并传递给控制器​​以查看

[英]Spring: Map and pass value as object form to controller to view

我是 spring 的新手,正在尝试通过表单中的单选按钮将字符串值传递给控制器​​,然后传递给视图。 如果控制器 @RequestParam 类型是字符串,我可以毫无问题地做到这一点。 但是我接下来要做的是将单选按钮属性值映射到一个对象,例如:

@Component
public class ChoiceBean {
    private String choice;

    public String getChoice() {
        return choice;
    }

    public void setChoice(String choice) {
        this.choice = choice;
    }

    @Override
    public String toString() {
        return "ChoiceBean{" + "choice=" + choice + '}';
    }
}

...但它在视图中返回 null。 我究竟做错了什么?

我用来更新我的控制器方法 getChoice() 和 processChoiceGet()。

这是我的文件:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
            http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany</groupId>
    <artifactId>flashcards-springboot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>flashcards-springboot</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

html中的表单

<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>
            <form action="processChoice" method="post">
                <input type="radio" name="choicebean" value="1" checked=true>1<br>
                <input type="radio" name="choicebean" value="2">2<br>
                <input type="submit" value="Submit"/>
            </form> 
        </div>
    </body>
</html>

控制器

@Controller
public class FileUploadController {

    private static final Logger slf4jLogger
            = LoggerFactory.getLogger(FileUploadController.class);

    // Holds keys, values in order
    Map<String, String> map = new LinkedHashMap<>();

    @Autowired
    private Utils utils;

    @Autowired
    ChoiceBean choiceBean;

    @GetMapping("/")
    public String home() throws IOException {
        return "home";
    }

    // Called from home view
    @PostMapping("/upload")
    public String handleFileUpload(
            @RequestParam("file") MultipartFile file, Model model) {
        // Clear map in case of new file upload
        map.clear();
        try {
            // Add map to model
            model.addAttribute("theMap",
                    utils.mapInputStringToMap(file.getBytes()));
        } catch (IOException ex) {
            slf4jLogger.error(FileUploadController.class.getName(), ex.getCause());
        }
        return "choice-1";
    }

    // Map object to attribute
    @ModelAttribute("choice")
    public ChoiceBean getChoice(HttpServletRequest request) 
    {
        return (ChoiceBean) request.getAttribute("choicebean");
    }

    @PostMapping("/processChoice")
    public String processChoiceGet(
        @ModelAttribute("choice") ChoiceBean choice, Model model) {

        // Log
        slf4jLogger.info("result: " + choice.getChoice());
        model.addAttribute("choice",choice.getChoice());
        return "flash-card";  
}

输出视图

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Getting Started: Serving Web Content</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <p th:text="'Hello, ' + ${choice} + '!'" />
    </body>
</html>

编辑:我在handleFileUpload() [<-this有效]中添加了一组数字,用作单选按钮显示; 还从选择中删除了 getString():

@Controller
public class FileUploadController {

    private static final Logger slf4jLogger
            = LoggerFactory.getLogger(FileUploadController.class);

    // Holds keys, values in order
    Map<String, String> map = new LinkedHashMap<>();

    @Autowired
    private Utils utils;
    @Autowired
    ChoiceBean choiceBean;

    @GetMapping("/")
    public String home() throws IOException {
        return "home";
    }

    // Called from home view
    @PostMapping("/upload")
    public String handleFileUpload(
            @RequestParam("file") MultipartFile file, Model model) {
        // Clear map in case of new file upload
        map.clear();
        try {
            // Add map to model
            model.addAttribute("theMap",
                    utils.mapInputStringToMap(file.getBytes()));
            model.addAttribute("sources", new String[]{"1", "2"});

        } catch (IOException ex) {
            slf4jLogger.error(FileUploadController.class.getName(), ex.getCause());
        }
        return "choice-1";
    }

    @ModelAttribute("choice")
    public ChoiceBean getChoice(HttpServletRequest request) 
    {
        return (ChoiceBean) request.getAttribute("choicebean");
    }

    @PostMapping("/processChoice")
    public String processChoiceGet(
        @ModelAttribute("choice") ChoiceBean choice, Model model) {

        // Log
        slf4jLogger.info("result: " + choice);
        model.addAttribute("choice",choice);
        return "flash-card";
    }
}

...并编辑表单以尝试将命令对象捕获为“选择”,但视图中的值仍然为空。 如何将选定的单选按钮值作为字符串显示在视图中?

<form th:object="${choice}" th:action="@{/processChoice}" method="post">
    <div th:each="source : ${sources}">
        <input name="source" type="radio" th:value="${source}"/>
        <label th:for="source" th:text="${source}">my label</label>
    </div>
    <input type="submit" value="Submit"/>
</form> 

你需要使用th:each

<input type="radio" th:each="me : ${choice}" th:value="${me.choice}">

感谢 José Bardales 的建议。 我能够使用它来使百里香叶单选按钮显示正确,但是我无法在视图中获得选定的值,所以我最终使用了一个普通的 html 表单。

下面是我的解决方案。 它有效,但我觉得控制器中有更好的方法可以将单选按钮值绑定到 Spring 中的 choicebean 对象,但不确定。

豆角,扁豆...

@Component
public class ChoiceBean {
    private String choice;
    // Getter, setter
}

形式...

<form action="processChoice" method="get">
    <input type="radio" name="radiochoice1" value="1" checked=true>1<br>
    <input type="radio" name="radiochoice1" value="2">2<br>
    <input type="submit" value="Submit"/>
</form>

控制器...

public String processChoiceGet(@RequestParam String radiochoice1,
        ChoiceBean choice, Model model) {
    choice.setChoice(radiochoice1);
    model.addAttribute("choice",choice);
    return "flash-card";

看法...

<body>
    <p th:text="'choice is ' + ${choice.choice} + '!'" />
</body>

暂无
暂无

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

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