java - 如何在我的 Controller Spring Boot 中获取输入表单中的值

标签 java spring spring-boot thymeleaf

您好,我想在表单中重新设置登录名和密码值

 <form action="#"  modelAttribute="authentification"  th:action="@{/user/add}"    method="post">
<div class="form-group">
<label for="exampleInputEmail1">prenom</label>
<input type="text" class="form-control" id="prenom"  name="prenom" placeholder="prenom">

</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password" name="password"   placeholder="Password">
</div>



<button type="submit" class="btn btn-primary">Submit</button>

<button type="button" class="btn btn-link">Nouveau Client je M'inscris</button>
</form>

确切地说,我想恢复我输入的密码和 prenom 的值,但我没有找到执行此操作的好方法

Controller :

@Autowired
UserImplementation ui;

@PostMapping("/add")
public String authentification(  Model m ,@PathVariable final String nom)
{

List<Utilisateur> user;

 user =ui.getuser();
m.addAttribute("Utilisateur", ui.getuser());

for(Utilisateur u : user)
{
    if(u.getPrenom().equals(nom))
    {
        return"clienthome";
    }
    else {
        int i =10;
        m.addAttribute("i", i);
        return"index";
    }

}
return "index";

}

最佳答案

您的 PostMapping 方法 authentification 中预计参数错误。您可以执行以下操作,以便能够在 Controller 方法中获取 HTML 输入数据。

这里我假设您的 prenompassword 属性包含在名为 User 的对象中。

@PostMapping("/add")
public String authentification(@ModelAttribute("authentification") User user) {
    // Your mentioned business logic
}

如果您的 prenompassword 属性不包含在对象中,而只是您尝试获取的 String,那么您可以执行以下操作:

@PostMapping("/add")
public String authentification(@RequestParam String prenom, @RequestParam String password) {
    // Your mentioned business logic
}

两个字符串 prenompassword 的名称必须等于 HTML 文件中特定属性的 name 标记(即 name="prenom"name="password"),否则您将收到 null 作为 Controller 方法中不同命名属性的参数。

如果您想要将 HTML 名称绑定(bind)到 HTML 属性,但想要将 Controller 方法参数命名为不同的名称,则 @RequestParam 注释提供了一种指定预期 HTML 的方法将其绑定(bind)到的参数名称。例如。 @RequestParam("prenom") String SomethingDifferent 会将 somethingDifferent 绑定(bind)到名为 prenom 的 HTML 属性。

关于java - 如何在我的 Controller Spring Boot 中获取输入表单中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010487/

相关文章:

java - 用Spring配置抽象工厂的实现类

java - Spring ReloadableResourceBundleMessageSource VS ResourceBundleMessageSource

java - 从我的日期变量中删除时间

java - 没有收到基于我输入的用户输入的任何输出。

spring - 如何读取 Spring Boot Controller 中的发布数据?

spring-boot - 解决启用Kotlin的项目中的Jhipster依赖项时出错

java - 基于命令行参数的多个 Spring boot CommandLineRunner

java - 如何在文本文件(如数据库)中获取和写入数据

java - 接口(interface)的Spring依赖注入(inject)

spring - 带变量的 thymeleaf 绝对 URL