Spring Boot中如何获取RequestParam里单个复选框状态值并传入ModelAndView
Spring Boot获取单个复选框状态并传入ModelAndView
首先,你的HTML需要包裹在<form>标签内才能提交参数到控制器,修改后的示例如下:
<html> <body> <form method="post" action="/handle-checkbox"> <label> <input type="checkbox" name="postcheckbox" /> demo checkbox </label> <button type="submit">提交</button> </form> </body> </html>
控制器处理逻辑
方式一:利用@RequestParam默认值
Spring Boot中,复选框选中时会提交postcheckbox参数(默认值为on,框架会自动转为boolean类型的true);未选中时不会提交该参数,因此可以通过设置defaultValue来指定未选中时的默认值:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class CheckboxController { @PostMapping("/handle-checkbox") public ModelAndView handleCheckboxSubmit( @RequestParam(name = "postcheckbox", defaultValue = "false") boolean isChecked) { ModelAndView modelAndView = new ModelAndView("result"); // 指定跳转的视图名称 modelAndView.addObject("checkboxStatus", isChecked); // 将复选框状态存入模型 return modelAndView; } }
方式二:通过HttpServletRequest手动判断
也可以直接通过请求对象判断参数是否存在,以此确定复选框状态:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @Controller public class CheckboxController { @PostMapping("/handle-checkbox") public ModelAndView handleCheckboxSubmit(HttpServletRequest request) { boolean isChecked = request.getParameter("postcheckbox") != null; ModelAndView modelAndView = new ModelAndView("result"); modelAndView.addObject("checkboxStatus", isChecked); return modelAndView; } }
视图层展示状态
以Thymeleaf模板为例,在result.html中可以取出模型中的状态值进行展示:
<html> <body> <h3>复选框状态:</h3> <p th:text="${checkboxStatus ? '已选中' : '未选中'}"></p> </body> </html>
如果使用JSP等其他模板引擎,直接通过${checkboxStatus}即可获取状态值。
内容的提问来源于stack exchange,提问作者Deep Shah
相关产品推荐
相关产品推荐

