• Spring Boot中Spring MVC的表单标签库与数据绑定讲解与实战(附源码 超详细必看)


    简介

    数据绑定是将用户参数输入值绑定到领域模型的一种特性。在Spring MVC的Controller和View参数数据传递中,所有HTTP请求参数的类型均为字符串。如果模型需要绑定的类型为double或int,则需要手动进行类型转换。而有了数据绑定后,就不再需要手动将HTTP请求中String类型转换为模型需要的类型。数据绑定的另一个好处是,当输入验证失败时,会重新生成一个HTML表单,无需重新填入输入字段

    在Spring MVC中,为了方便 高效的使用数据绑定,还需要学习表单标签库

    表单标签库

    表单标签库中包含可以用在JSP页面中渲染HTML元素的标签,JSP页面使用Spring表单标签库时,必须在JSP页面开头处声明taglib指令 代码如下

    <%taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

    表单包含元素如下 

     数据绑定

    1:创建ch2_4应用并导入相关的JAR包

    2:创建Web和Spring MVC配置类

    在src目录下创建名为config的包 并创建WebConfig和SpringMVCConfig配置类

    Webconfig代码如下

    1. package config;
    2. import javax.servlet.ServletContext;
    3. import javax.servlet.ServletException;
    4. import org.springframework.web.WebApplicationInitializer;
    5. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    6. import org.springframework.web.filter.CharacterEncodingFilter;
    7. import org.springframework.web.servlet.DispatcherServlet;
    8. public class WebConfig implements WebApplicationInitializer{
    9. @Override
    10. public void onStartup(ServletContext arg0) throws ServletException {
    11. AnnotationConfigWebApplicationContext ctx
    12. = new AnnotationConfigWebApplicationContext();
    13. ctx.register(SpringMVCConfig.class);//注册Spring MVC的Java配置类SpringMVCConfig
    14. ctx.setServletContext(arg0);//和当前ServletContext关联
    15. /**
    16. * 注册Spring MVC的DispatcherServlet
    17. */
    18. javax.servlet.ServletRegistration.Dynamic servlet =
    19. arg0.addServlet("dispatcher", new DispatcherServlet(ctx));
    20. servlet.addMapping("/");
    21. servlet.setLoadOnStartup(1);
    22. /**
    23. * 注册字符编码过滤器
    24. */
    25. javax.servlet.FilterRegistration.Dynamic filter =
    26. arg0.addFilter("characterEncodingFilter", CharacterEncodingFilter.class);
    27. filter.setInitParameter("encoding", "UTF-8");
    28. filter.addMappingForUrlPatterns(null, false, "/*");
    29. }
    30. }

    SpringMVCConfig代码如下

    1. package config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.ComponentScan;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    6. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    8. import org.springframework.web.servlet.view.InternalResourceViewResolver;
    9. @Configuration
    10. @EnableWebMvc
    11. @ComponentScan(basePackages = {"controller","service"})
    12. public class SpringMVCConfig implements WebMvcConfigurer {
    13. /**
    14. * 配置视图解析器
    15. */
    16. @Bean
    17. public InternalResourceViewResolver getViewResolver() {
    18. InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    19. viewResolver.setPrefix("/WEB-INF/jsp/");
    20. viewResolver.setSuffix(".jsp");
    21. return viewResolver;
    22. }
    23. /**
    24. * 配置静态资源
    25. */
    26. @Override
    27. public void addResourceHandlers(ResourceHandlerRegistry registry) {
    28. registry.addResourceHandler("/html/**").addResourceLocations("/html/");
    29. //addResourceHandler指的是对外暴露的访问路径
    30. //addResourceLocations指的是静态资源存放的位置
    31. }
    32. }

    3:创建View层

    包含两个JSP页面 一个是信息输入页面userAdd.jsp 一个是信息显示页面userList.jsp

    userAdd.jsp代码如下

    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    3. <!DOCTYPE html>
    4. <html>
    5. <head>
    6. <meta charset="UTF-8">
    7. <title>Insert title here</title>
    8. </head>
    9. <body>
    10. <form:form modelAttribute="user" method="post" action=" ${pageContext.request.contextPath }/user/save">
    11. <fieldset>
    12. <legend>添加一个用户</legend>
    13. <p>
    14. <label>用户名:</label>
    15. <form:input path="userName"/>
    16. </p>
    17. <p>
    18. <label>爱好:</label>
    19. <form:checkboxes items="${hobbys}" path="hobby" />
    20. </p>
    21. <p>
    22. <label>朋友:</label>
    23. <form:checkbox path="friends" value="张三"/>张三
    24. <form:checkbox path="friends" value="李四"/>李四
    25. <form:checkbox path="friends" value="王五"/>王五
    26. <form:checkbox path="friends" value="赵六"/>赵六
    27. </p>
    28. <p>
    29. <label>职业:</label>
    30. <form:select path="carrer">
    31. <option/>请选择职业
    32. <form:options items="${carrers }"/>
    33. </form:select>
    34. </p>
    35. <p>
    36. <label>户籍:</label>
    37. <form:select path="houseRegister">
    38. <option/>请选择户籍
    39. <form:options items="${houseRegisters }"/>
    40. </form:select>
    41. </p>
    42. <p>
    43. <label>个人描述:</label>
    44. <form:textarea path="remark" rows="5"/>
    45. </p>
    46. <p id="buttons">
    47. <input id="reset" type="reset">
    48. <input id="submit" type="submit" value="添加">
    49. </p>
    50. </fieldset>
    51. </form:form>
    52. </body>
    53. </html>

    userList.jsp代码如下

    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    3. <!DOCTYPE html>
    4. <html>
    5. <head>
    6. <meta charset="UTF-8">
    7. <title>Insert title here</title>
    8. </head>
    9. <body>
    10. <h1>用户列表</h1>
    11. <a href="/user/input"/>">继续添加</a>
    12. <table>
    13. <tr>
    14. <th>用户名</th>
    15. <th>兴趣爱好</th>
    16. <th>朋友</th>
    17. <th>职业</th>
    18. <th>户籍</th>
    19. <th>个人描述</th>
    20. </tr>
    21. <!-- JSTL标签,请参考本书的相关内容 -->
    22. <c:forEach items="${users}" var="user">
    23. <tr>
    24. <td>${user.userName }</td>
    25. <td>
    26. <c:forEach items="${user.hobby }" var="hobby">
    27. ${hobby }&nbsp;
    28. </c:forEach>
    29. </td>
    30. <td>
    31. <c:forEach items="${user.friends }" var="friend">
    32. ${friend }&nbsp;
    33. </c:forEach>
    34. </td>
    35. <td>${user.carrer }</td>
    36. <td>${user.houseRegister }</td>
    37. <td>${user.remark }</td>
    38. </tr>
    39. </c:forEach>
    40. </table>
    41. </body>
    42. </html>

    4:创建领域模型

    在src目录下创建pojo包 并创建User类

    1. package pojo;
    2. public class User {
    3. private String userName;
    4. private String[] hobby;//兴趣爱好
    5. private String[] friends;//朋友
    6. private String carrer;
    7. private String houseRegister;
    8. private String remark;
    9. public String getUserName() {
    10. return userName;
    11. }
    12. public void setUserName(String userName) {
    13. this.userName = userName;
    14. }
    15. public String[] getHobby() {
    16. return hobby;
    17. }
    18. public void setHobby(String[] hobby) {
    19. this.hobby = hobby;
    20. }
    21. public String[] getFriends() {
    22. return friends;
    23. }
    24. public void setFriends(String[] friends) {
    25. this.friends = friends;
    26. }
    27. public String getCarrer() {
    28. return carrer;
    29. }
    30. public void setCarrer(String carrer) {
    31. this.carrer = carrer;
    32. }
    33. public String getHouseRegister() {
    34. return houseRegister;
    35. }
    36. public void setHouseRegister(String houseRegister) {
    37. this.houseRegister = houseRegister;
    38. }
    39. public String getRemark() {
    40. return remark;
    41. }
    42. public void setRemark(String remark) {
    43. this.remark = remark;
    44. }
    45. }

    5:创建Service层

    Service层使用静态集合变量users模拟数据库存储用户信息,包括添加用户和查询用户两个功能

    UserService接口类代码如下

    1. package service;
    2. import java.util.ArrayList;
    3. import pojo.User;
    4. public interface UserService {
    5. boolean addUser(User u);
    6. ArrayList getUsers();
    7. }

    UserServiceImpl实现类代码如下

    1. package service;
    2. import java.util.ArrayList;
    3. import org.springframework.stereotype.Service;
    4. import pojo.User;
    5. @Service
    6. public class UserServiceImpl implements UserService{
    7. //使用静态集合变量users模拟数据库
    8. private static ArrayList users = new ArrayList();
    9. @Override
    10. public boolean addUser(User u) {
    11. if(!"IT民工".equals(u.getCarrer())){//不允许添加IT民工
    12. users.add(u);
    13. return true;
    14. }
    15. return false;
    16. }
    17. @Override
    18. public ArrayList getUsers() {
    19. return users;
    20. }
    21. }

    6:创建Controller层

    在Controller类的UserController中定义了请求处理方法 代码如下

    1. package controller;
    2. import java.util.HashMap;
    3. import java.util.List;
    4. import org.apache.commons.logging.Log;
    5. import org.apache.commons.logging.LogFactory;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Controller;
    8. import org.springframework.ui.Model;
    9. import org.springframework.web.bind.annotation.ModelAttribute;
    10. import org.springframework.web.bind.annotation.RequestMapping;
    11. import pojo.User;
    12. import service.UserService;
    13. @Controller
    14. @RequestMapping("/user")
    15. public class UserController {
    16. // 得到一个用来记录日志的对象,这样打印信息的时候能够标记打印的是那个类的信息
    17. private static final Log logger = LogFactory.getLog(UserController.class);
    18. @Autowired
    19. private UserService userService;
    20. @RequestMapping(value = "/input")
    21. public String inputUser(Model model) {
    22. HashMap<String, String> hobbys = new HashMap<String, String>();
    23. hobbys.put("篮球", "篮球");
    24. hobbys.put("乒乓球", "乒乓球");
    25. hobbys.put("电玩", "电玩");
    26. hobbys.put("游泳", "游泳");
    27. // 如果model中没有user属性,userAdd.jsp会抛出异常,因为表单标签无法找到
    28. // modelAttribute属性指定的form backing object
    29. model.addAttribute("user", new User());
    30. model.addAttribute("hobbys", hobbys);
    31. model.addAttribute("carrers", new String[] { "教师", "学生", "coding搬运工", "IT民工", "其它" });
    32. model.addAttribute("houseRegisters", new String[] { "北京", "上海", "广州", "深圳", "其它" });
    33. return "userAdd";
    34. }
    35. @RequestMapping(value = "/save")
    36. public String addUser(@ModelAttribute User user, Model model) {
    37. if (userService.addUser(user)) {
    38. logger.info("成功");
    39. return "redirect:/user/list";
    40. } else {
    41. logger.info("失败");
    42. HashMap<String, String> hobbys = new HashMap<String, String>();
    43. hobbys.put("篮球", "篮球");
    44. hobbys.put("乒乓球", "乒乓球");
    45. hobbys.put("电玩", "电玩");
    46. hobbys.put("游泳", "游泳");
    47. // 这里不需要model.addAttribute("user", new
    48. // User()),因为@ModelAttribute指定form backing object
    49. model.addAttribute("hobbys", hobbys);
    50. model.addAttribute("carrers", new String[] { "教师", "学生", "coding搬运工", "IT民工", "其它" });
    51. model.addAttribute("houseRegisters", new String[] { "北京", "上海", "广州", "深圳", "其它" });
    52. return "userAdd";
    53. }
    54. }
    55. @RequestMapping(value = "/list")
    56. public String listUsers(Model model) {
    57. List<User> users = userService.getUsers();
    58. model.addAttribute("users", users);
    59. return "userList";
    60. }
    61. }

    7:测试应用 启动主类后 通过地址

    http://localhost:8080/ch2_4/user/input测试应用接口

     测试效果如下

     

  • 相关阅读:
    prometheus k8s服务发现
    stm32—GPIO
    基于javaweb的医院门诊查询系统(前端+后端)
    弘辽科技:看了这些,你就知道为什么你的淘宝店铺做不起来
    ElasticStack日志分析平台-ES 集群、Kibana与Kafka
    spring循环依赖-不仅仅是八股文
    EEG时频主成分分析(TF-PCA)实用教程(附示例数据和代码)
    openssl生成key和pem文件
    百分点科技再度亮相GITEX全球大会
    网络编程三要素
  • 原文地址:https://blog.csdn.net/jiebaoshayebuhui/article/details/127640218