SpringMVC数据绑定

参考应用ch4创建应用practice44。在应用practice44中创建两个视图页面addGoods.jsp和goodsList.jsp。addGoods.jsp页面的显示效果如图4.5所示,goodsList.jsp页面的显示效果如图4.6所示。
在这里插入图片描述
图4.5 添加商品页面

在这里插入图片描述
图4.6 商品显示页面
​ 具体要求:

1.商品类型由控制器类GoodsController的方法inputGoods进行初始化。GoodsController类中共有三个方法:inputGoods、addGoods和listGoods。

2.使用Goods模型类封装请求参数。

3.使用Service层,在Service的实现类中,使用静态集合变量模拟数据库存储商品信息,在控制器类中使用@Autowired注解Service。

​ 4.通过地址http://localhost:8080/practice44/goods/input访问addGoods.jsp页面。

​ 5.其他的注意事项参见应用ch4。

1.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>springmvc_10</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc_servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc_10</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 避免中文乱码 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2.在resources目录下配springmvc_servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.sxau2.controller"/>
    <context:component-scan base-package="com.sxau2.servlet"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.在WEB-INF目录下新建jsp文件夹

4.在java目录下新建com.sxau2包并在子目录下新建Controller、pojo、servlet包

Controller包下新建GoodsController.java

package com.sxau2.controller;

import com.sxau2.pojo.Goods;
import com.sxau2.servlet.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @RequestMapping("/add")
    public String add(Model model){
        Goods goods = new Goods();
        model.addAttribute("goods",goods);
        model.addAttribute("goodsTypes",new String[]{"电器","食品","家居","数码"});
        return "goodsAdd";
    }

    @RequestMapping("/save")
    public String save(@ModelAttribute Goods goods,Model model){
        if (goodsService.addGoods(goods)){
            return "redirect:/goods/list";
        }else return "/goods/add";
    }
    @RequestMapping("/list")
    public String list(Model model){
        ArrayList<Goods> goods = goodsService.listGoods();
        System.out.println(goods.toString());
        model.addAttribute("listgoods",goods);
        return "goodsList";
    }
}

pojo包下新建Goods.java实体类

package com.sxau2.pojo;

public class Goods {
    String goodsName;
    String goodsPrice;
    String goodsType;

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getGoodsPrice() {
        return goodsPrice;
    }

    public void setGoodsPrice(String goodsPrice) {
        this.goodsPrice = goodsPrice;
    }

    public String getGoodsType() {
        return goodsType;
    }

    public void setGoodsType(String goodsType) {
        this.goodsType = goodsType;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "goodsName='" + goodsName + '\'' +
                ", goodsPrice='" + goodsPrice + '\'' +
                ", goodsType='" + goodsType + '\'' +
                '}';
    }
}

service业务层新建GoodsService.java

package com.sxau2.servlet;

import com.sxau2.pojo.Goods;

import java.util.ArrayList;

public interface GoodsService {

    boolean addGoods(Goods goods);

    ArrayList<Goods> listGoods();
}

service业务层新建Impl包并在包下新建GoodsServiceImpl.java

package com.sxau2.servlet.impl;

import com.sxau2.pojo.Goods;
import com.sxau2.servlet.GoodsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
@Service
public class GoodsServiceImpl implements GoodsService {
    private static ArrayList<Goods> goodsList = new ArrayList<Goods>();
    @Override
    public boolean addGoods(Goods goods) {
        goodsList.add(goods);
        return true;
    }

    @Override
    public ArrayList<Goods> listGoods() {
        return goodsList;
    }
}

5.编写前端首页index.jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 张晟睿
  Date: 2021/6/13
  Time: 16:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body bgcolor="#ffc0cb">
  <p align="center">欢迎来到首页</p>
  <p align="center"><a href="/goods/add">跳转到商品首页</a></p>
  </body>
</html>

6.在jsp文件夹下新建goodsAdd.jsp、goodsList.jsp

goodsAdd.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: 张晟睿
  Date: 2021/6/13
  Time: 16:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form:form modelAttribute="goods" action="/goods/save" method="post">
    <table border="1">
        <tr>
            <td>商品名称:</td>
            <td><form:input path="goodsName"/></td>
        </tr>
        <tr>
            <td>商品价格:</td>
            <td><form:input path="goodsPrice"/></td>
        </tr>
        <tr>
            <td>商品类型:</td>
            <td>
                <form:select path="goodsType">
                    <option/>请选择
                    <form:options items="${goodsTypes}"/>
                </form:select>
            </td>
        </tr>
        <tr>
            <td><input type="submit" value="提交"/> </td>
            <td><input type="reset" value="重置"/> </td>
        </tr>
    </table>
</form:form>
</body>
</html>

goodsList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 张晟睿
  Date: 2021/6/13
  Time: 16:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>商品展示</h1>
<a href="/goods/add">继续添加</a>
<table border="1">
    <tr>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>商品类型</th>
    </tr>
    <c:forEach items="${listgoods}" var="goods">
        <tr>
            <td>${goods.goodsName}</td>
            <td>${goods.goodsPrice}</td>
            <td>${goods.goodsType}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

7.运行注意事项:

地址栏:http://localhost:8080/

增加商品栏地址:http://localhost:8080/goods/add

商品展示地址:http://localhost:8080/goods/list

运行截图:

在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
Spring MVC 数据绑定是指将客户端提交的数据绑定到 Controller 中的方法参数或类属性上,从而方便地获取表单数据并进行处理。 Spring MVC 数据绑定主要分为两种类型: 1. 基本类型数据绑定:将客户端提交的基本类型数据(如字符串、整数、布尔型等)绑定到 Controller 中的方法参数上。 例如: ```java @RequestMapping("/login") public String login(String username, String password) { // do something } ``` 2. 对象类型数据绑定:将客户端提交的表单数据绑定到 Controller 中的 POJO(Plain Old Java Object,普通 Java 对象)上。 例如: ```java @RequestMapping("/register") public String register(User user) { // do something } ``` 在对象类型数据绑定中,Spring MVC 默认使用 JavaBean 规范的 setter 方法进行属性赋值,例如: ```java public class User { private String username; private String password; // 省略 getter 和 setter 方法 } ``` 当客户端提交的表单数据中包含 username 和 password 参数时,Spring MVC 将自动调用 User 类中对应的 setter 方法将数据绑定到 User 对象中。 除了默认的 setter 方法,Spring MVC 支持使用自定义的属性编辑器(PropertyEditor)来实现数据类型转换和数据格式化等功能。例如,可以通过自定义属性编辑器将字符串类型的日期转换为 Date 类型。 要使用自定义的属性编辑器,需要在 Controller 类中注册 PropertyEditor 实例: ```java @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } ``` 上面代码中,我们注册了一个 SimpleDateFormat 类型的属性编辑器,并将其注册到 WebDataBinder 中。然后,我们在 Controller 中的方法参数上使用 Date 类型来接收客户端提交的日期数据,Spring MVC 将自动根据我们注册的属性编辑器将字符串类型的日期转换为 Date 类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java厂长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值