SpringMVC的格式化转换器Formatter

SpringMVC的格式化转换器Formatter

SpringMVC框架的Formatter和Converter一样,也是一个可以将一种数据类型转换成另外一种数据类型的接口,不同的是Formatter的数据源必须是String类型,而Converter源数据类型可以是任意的。

因为在WEB应用中由http发送的请求数据到控制器都是以String类型获取,因此在Web应用中选择Formatter比选择Converter更合理。

下面演示一个用户在信息采集页面输入数据,创建商品信息,控制器类接收请求参数,并调用格式化转换器完成转换,最后显示在show.jsp页面。

1-创建web应用,并导入相关jar包。
2-在index.jsp页面采集数据,并映射到相应的控制器。

<%--
  Created by IntelliJ IDEA.
  User: nuist__NJUPT
  Date: 2021/9/29
  Time: 8:40
  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 action="${pageContext.request.contextPath}/my/formatter" method="post">
    请输入商品信息<br>
    商品名称:<input type = "text" name = "goodsName"/><br>
    商品价格:<input type = "text" name = "goodsPrice"/><br>
    商品数量:<input type = "text" name = "goodsNumber"/><br>
    商品日期:<input type = "text" name = "goodsDate"/><br>
    <input type = "submit" value = "提交"/>
  </form>
  </body>
</html>

3-在web.xml中部署DisparcherServlet,用于整体控制。

<?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"
         id = "WebApp_ID" version="4.0">
    <!--部署DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/springmvc-servlet.xml</param-value>
        </init-param>
        <!--表示容器启动时加载的servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--任意的请求都通过DispatcherServlet-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 配置 CharacterEncodingFilter解决中文乱码问题-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <!-- 配置编码格式为UTF-8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>


4-创建pojo包,在该包中创建商品信息类,用于传递参数。

import java.util.Date;

/**

 */
public class GoodsMeal {
    private String goodsName ;
    private double goodsPrice ;
    private int goodsNumber ;
    private Date goodsDate ;

    public Date getGoodsDate() {
        return goodsDate;
    }

    public void setGoodsDate(Date goodsDate) {
        this.goodsDate = goodsDate;
    }

    public String getGoodsName() {
        return goodsName;
    }

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

    public double getGoodsPrice() {
        return goodsPrice;
    }

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

    public int getGoodsNumber() {
        return goodsNumber;
    }

    public void setGoodsNumber(int goodsNumber) {
        this.goodsNumber = goodsNumber;
    }
}

5-创建controller包,在该包中创建控制器类,用于接收参数,暴露模型数据,同时进入信息展示页面。


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.GoodsMeal;

@Controller
@RequestMapping("/my")
public class FormatterController {
    @RequestMapping("/formatter")
    public String myFormatter(GoodsMeal gm, Model model){
        model.addAttribute("goods", gm) ;
        return "show" ;
    }
}

6-创建formatter包,在该包中创建格转换器类,完成转换。


import org.springframework.format.Formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MyFormatter  implements Formatter<Date> {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
    @Override
    public Date parse(String s, Locale locale) throws ParseException { //利用指定的Locale将一个String类型转换成目标类型
        return dateFormat.parse(s);
    }

    @Override
    public String print(Date date, Locale locale) { //返回目标对象的字符串表示
        return dateFormat.format(date);
    }
}

7-在WEB-INF目录下创建配置文件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
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--使用扫描机制,扫描控制器类-->
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>
    <!--注册类型转换器GoodsConverter-->
    <bean id = "conversionService" class = "org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name = "formatters">
            <list>
                <bean class = "formatter.MyFormatter"/>
            </list>
        </property>
    </bean>
    <!--启动注册的类型转换器-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--annotation-driven用于简化开发的配置,注解DefaultAnnotationHandlerMappingAnnotationMethodHandlerAdapter-->
    <!--使用resources过滤掉不需要dispatcherservlet的资源,例如静态资源,在使用resources时必须使用annotation-driven,否则resources会阻止任意控制器被调用-->


    <!--配置视图解析器-->
    <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" id = "internalResourceViewResolver">
        <!--前缀-->
        <property name = "prefix" value = "/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name = "suffix" value = ".jsp"/>
    </bean>
</beans>



8-在WEB-INF目录下创建show.jsp页面,使用E表达式取出goods的属性值。

<%--
  Created by IntelliJ IDEA.
  User: nuist__NJUPT
  Date: 2021/9/29
  Time: 10:59
  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>
<!--使用EL表达式取出goods属性值-->
商品名称:${goods.goodsName}<br>
商品价格:${goods.goodsPrice}<br>
商品数量:${goods.goodsNumber}<br>
商品日期:${goods.goodsDate}
</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

nuist__NJUPT

给个鼓励吧,谢谢你

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

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

打赏作者

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

抵扣说明:

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

余额充值