Spring MVC type Converter

Keywords: Java Spring mvc

Spring MVC type Converter

In the spring MVC framework, you need to collect user request parameters and pass them to the application controller component. All request parameters can only be string data types. The spring MVC framework must Convert these strings into corresponding data types. Generally, JSP+Servlet requires the developer to perform type conversion in the servlet and encapsulate it into objects, which is cumbersome. For the spring MVC framework, he must Convert the request parameters into the data types corresponding to each attribute in the value object. The spring MVC Convert is an interface that can Convert one data type into another, Generally, developers can use the built-in type converter in the framework in practical applications, but sometimes they need to write type converters with specific functions

  • Note: when using the built-in converter, the input value of the request parameter should be consistent with the type of the received parameter, otherwise an error will be reported.

Here is a demonstration of a custom Converter type Converter.
1 - create a web application and import relevant jar packages.
2 - create an input information collection view on the index.jsp page. After clicking the submit button, the view will be mapped to the corresponding controller for processing.

<%--
  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/converter" method="post">
Please enter product information(Format is apple,110.58,200)
  <input type = "text" name = "goodsMeal"/><br>
  <input type = "submit" value = "Submit"/>
  </form>
  </body>
</html>

3 - create a pojo package in which GoodsMeal class is created to pass parameters to the controller

public class GoodsMeal {
    private String goodsName ;
    private double goodsPrice ;
    private int goodsNumber ;

    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;
    }
}

4 - create the controller package and create the controller class in the package
ConverterController is used to receive request parameters and convert corresponding parameters to corresponding types.

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 ConverterController {
    @RequestMapping("/converter")
    public String myConverter(GoodsMeal gm, Model model){
        model.addAttribute("goodsMeal", gm) ;
        return "showGoods" ;
    }
}

5 - create converter package, create custom type changer in the modified package, and complete type conversion.

import org.springframework.core.convert.converter.Converter;
import pojo.GoodsMeal;

//Source type, String type, target type GoodsMeal
public class GoodsConverter implements Converter<String, GoodsMeal> {
    @Override
    public GoodsMeal convert(String s) {
        GoodsMeal goodsMeal = new GoodsMeal() ;
        String [] values = s.split(",") ;
        if(values != null && values.length == 3){
            goodsMeal.setGoodsName(values[0]) ;
            goodsMeal.setGoodsPrice(Double.parseDouble(values[1])) ;
            goodsMeal.setGoodsNumber(Integer.parseInt(values[2])) ;
            return goodsMeal ;
        }else{
            throw new IllegalArgumentException("Format conversion error") ;
        }
    }
}

6 - configure DispatcherServlet in web.xml for general control

<?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">
    <!--deploy 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>
        <!--Represents the load when the container starts servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--Any request passed DispatcherServlet-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

7 - create the configuration file springmvc-servlet.xml in the WEB-INF, scan the controller package in the configuration file to make the annotation effective, register the custom type converter, start the converter at the same time, and register the view parser.

<?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">

    <!--Using the scanning mechanism, scan the controller class-->
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>
    <!--Register type converter GoodsConverter-->
    <bean id = "conversionService" class = "org.springframework.context.support.ConversionServiceFactoryBean">
        <property name = "converters">
            <list>
                <bean class = "converter.GoodsConverter"/>
            </list>
        </property>
    </bean>
    <!--Start registered type converter-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--annotation-driven Configuration to simplify development,annotation DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter-->
    <!--use resources Filter out unnecessary dispatcherservlet Resources,For example, static resources are in use resources Must be used when annotation-driven,otherwise resources Prevents any controller from being called-->



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



8 - create a JSP directory under WEB-INF, create an information display page showGoods.jsp in this directory, and get the goodsMeal information in the model through EL expression on this page.

<%--
  Created by IntelliJ IDEA.
  User: nuist__NJUPT
  Date: 2021/9/29
  Time: 9:23
  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>
The product information you created is as follows:<br>
<!--use EL Expression fetch model Medium goodsMeal Information about-->
The name of the commodity is: ${goodsMeal.goodsName}
The price of the commodity is: ${goodsMeal.goodsPrice}
The quantity of goods is: ${goodsMeal.goodsNumber}
</body>
</html>

Working process: first, input the information through the index.jsp page and click Submit. The client request is submitted to the dispatcher servlet. The dispatcher servlet finds the Requestmapping and maps it to the specified controller. After the controller calls the custom type conversion class, it returns to ModelAndView. After the view parser parses, it enters the main page, The main page takes out the value of goodsMeal in the model object through EL expression.

Posted by taddis on Tue, 28 Sep 2021 18:34:31 -0700