SpringBoot+Freemarker:不使用Model从HTML取输入值到Controller
Spring Boot 不借助Model获取表单输入值到Controller的方法
针对你在Spring Boot项目中使用Freemarker模板,需要将表单中的fvalue和svalue输入值直接传递到Controller的需求,以下是几种可行的实现方式:
方法一:使用@RequestParam注解直接绑定参数
这是最直接的方式,通过@RequestParam将请求参数与Controller方法的参数一一绑定:
@PostMapping("/reportUpdate") public String reportToUpdate(@RequestParam("fvalue") String firstName, @RequestParam("svalue") String secondName) { // 在这里使用firstName和secondName进行业务逻辑处理 System.out.println("获取到fvalue:" + firstName); System.out.println("获取到svalue:" + secondName); return "Data saved!"; }
- 如果方法参数名和表单输入的
name属性完全一致,可以省略注解中的参数名,比如@RequestParam String fvalue。 - 若参数可能为空,可添加
required = false属性避免请求报错,例如@RequestParam(value = "fvalue", required = false) String firstName。
方法二:通过HttpServletRequest获取参数
如果你需要访问更多请求相关的信息,或者参数名称动态变化,可以直接注入HttpServletRequest来获取参数:
import javax.servlet.http.HttpServletRequest; @PostMapping("/reportUpdate") public String reportToUpdate(HttpServletRequest request) { String firstName = request.getParameter("fvalue"); String secondName = request.getParameter("svalue"); // 业务逻辑处理 return "Data saved!"; }
方法三:使用DTO对象绑定批量参数
如果表单字段较多,建议创建一个DTO(数据传输对象)来统一接收参数,代码会更整洁:
- 先定义DTO类:
public class PatientForm { private String fvalue; private String svalue; // 必须提供无参构造方法(Spring默认使用) public PatientForm() {} // Getter和Setter方法 public String getFvalue() { return fvalue; } public void setFvalue(String fvalue) { this.fvalue = fvalue; } public String getSvalue() { return svalue; } public void setSvalue(String svalue) { this.svalue = svalue; } }
- 在Controller中使用该DTO:
@PostMapping("/reportUpdate") public String reportToUpdate(PatientForm patientForm) { String firstName = patientForm.getFvalue(); String secondName = patientForm.getSvalue(); // 业务逻辑处理 return "Data saved!"; }
以上三种方式都不需要借助Model(Model主要用于向前端视图传递数据),均可直接获取表单提交的参数值。
内容的提问来源于stack exchange,提问作者Guhan
相关产品推荐
相关产品推荐

