Home > Java > javaTutorial > body text

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text

黄舟
Release: 2017-03-03 11:01:45
Original
1877 people have browsed it

In series (6) we introduced how to verify the correctness of the submitted data. When the data passes the verification, it will be saved by us. The saved data will be used for future display, which is the value of saving. So how to display it as required when displaying? (For example: retain a certain number of decimal digits, date in a specified format, etc.). This is what this article is about—>Formatted display.

Starting from Spring SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text. For conversion, Formatter SPI is an encapsulation of Converter SPI and adds support for internationalization. Its internal conversion is still completed by Converter SPI.

The following is a simple conversion process between a request and a model object:

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text

Spring provides FormattingConversionService and DefaultFormattingConversionService to complete object parsing and formatting. Several Formatter SPIs built into Spring are as follows:

##NameFunctionNumberFormatterRealize the parsing and formatting between Number and StringCurrencyFormatterRealize the parsing and formatting between Number and String (with currency symbol)PercentFormatterRealizes parsing and formatting between Number and String (with percent symbol)DateFormatterImplement the parsing and formatting between Date and StringNumberFormatAnnotationFormatterFactory@NumberFormat annotation, to realize the parsing and formatting between Number and String, can be specified by style to indicate the format to be converted (Style.Number/Style.Currency/Style.Percent). Of course, you can also specify pattern (such as pattern="#.##" (retaining SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text decimal places)), so that the format specified by pattern will Override the format specified by StyleJodaDateTimeFormatAnnotationFormatterFactory@DateTimeFormat annotation to implement parsing and formatting between date types and String. Date types here include Date, Calendar, Long and Joda date types. Joda-Time package must be added to the project

Let’s start the demonstration:

First add the Joda-Time package to the previous project. Here we use joda-time-SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text.SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text.jar, and add a formattest.jsp view under the views folder. , the content is as follows:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextC//DTD HTML SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text.0SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text Transitional//EN" "http://www.wSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text.org/TR/htmlSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text/loose.dtd"><meta><title>Insert title here</title>
Copy after login
    money:<br>${contentModel.money}<br>
    date:<br>${contentModel.date}<br>
Copy after login
    
Copy after login


SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text. First, we use Formatter directly for demonstration, and add FormatModel.java in the com.demo.web.models package with the following content:

package com.demo.web.models;public class FormatModel{    
    private String money;    private String date;    
    public String getMoney(){        return money;
    }    public String getDate(){        return date;
    }    
    public void setMoney(String money){        this.money=money;
    }    public void setDate(String date){        this.date=date;
    }
        
}
Copy after login


Add FormatController.java in the com.demo.web.controllers package with the following content:

package com.demo.web.controllers;import java.math.RoundingMode;import java.util.Date;import java.util.Locale;import org.springframework.context.iSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text8n.LocaleContextHolder;import org.springframework.format.datetime.DateFormatter;import org.springframework.format.number.CurrencyFormatter;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/format")public class FormatController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(Model model) throws NoSuchFieldException, SecurityException{        if(!model.containsAttribute("contentModel")){
            
            FormatModel formatModel=new FormatModel();

            CurrencyFormatter currencyFormatter = new CurrencyFormatter();  
            currencyFormatter.setFractionDigits(SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text);//保留SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text位小数
            currencyFormatter.setRoundingMode(RoundingMode.HALF_UP);//向(距离)最近的一边舍入,如果两边(的距离)是相等的则向上舍入(四舍五入)            
            DateFormatter dateFormatter=new DateFormatter();
            dateFormatter.setPattern("yyyy-MM-dd HH:mm:ss");
            
            Locale locale=LocaleContextHolder.getLocale();
            
            formatModel.setMoney(currencyFormatter.print(SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text5.678, locale));
            formatModel.setDate(dateFormatter.print(new Date(), locale));        
            
            model.addAttribute("contentModel", formatModel);
        }        return "formattest";
    }
    
}
Copy after login


Run the test:

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text

Change your preferred browser language:

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text

Refresh the page:

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text. This time use DefaultFormattingConversionService for demonstration, change FormatController.java to the following content:

package com.demo.web.controllers;import java.math.RoundingMode;import java.util.Date;import org.springframework.format.datetime.DateFormatter;import org.springframework.format.number.CurrencyFormatter;import org.springframework.format.support.DefaultFormattingConversionService;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/format")public class FormatController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(Model model) throws NoSuchFieldException, SecurityException{        if(!model.containsAttribute("contentModel")){
            
            FormatModel formatModel=new FormatModel();

            CurrencyFormatter currencyFormatter = new CurrencyFormatter();  
            currencyFormatter.setFractionDigits(SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text);//保留SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text位小数
            currencyFormatter.setRoundingMode(RoundingMode.HALF_UP);//向(距离)最近的一边舍入,如果两边(的距离)是相等的则向上舍入(四舍五入)            
            DateFormatter dateFormatter=new DateFormatter();
            dateFormatter.setPattern("yyyy-MM-dd HH:mm:ss");
            
            DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();  
            conversionService.addFormatter(currencyFormatter); 
            conversionService.addFormatter(dateFormatter); 
            
            formatModel.setMoney(conversionService.convert(SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text5.678, String.class));
            formatModel.setDate(conversionService.convert(new Date(), String.class));    
            
            model.addAttribute("contentModel", formatModel);
        }        return "formattest";
    }
    
}
Copy after login


##This time there is no Locale locale=LocaleContextHolder.getLocale( ); Run the test again and change the language and refresh. You can see the same effect as the screenshot of the first method, indicating that the DefaultFormattingConversionService will automatically return the corresponding format according to the information requested by the browser.

SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text. I guess some people may think, ah... I just want to format the display. Why should it be so troublesome to write code to convert field by field? ? ? Don’t worry, the above is just a demonstration of the built-in format converter. It will definitely not be used in actual projects. Here is an introduction to annotation-based formatting. First, change FormatModel.java to the following content:

package com.demo.web.models;import java.util.Date;import org.springframework.format.annotation.DateTimeFormat;import org.springframework.format.annotation.NumberFormat;import org.springframework.format.annotation.NumberFormat.Style;public class FormatModel{
    
    @NumberFormat(style=Style.CURRENCY)   private double money;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")    private Date date;    
    public double getMoney(){        return money;
    }    public Date getDate(){        return date;
    }    
    public void setMoney(double money){        this.money=money;
    }    public void setDate(Date date){        this.date=date;
    }
        
}
Copy after login


Note: The money and date here are no longer String types, but their own types.

Change FormatController.java to the following content:

package com.demo.web.controllers;import java.util.Date;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/format")public class FormatController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(Model model) throws NoSuchFieldException, SecurityException{        if(!model.containsAttribute("contentModel")){
            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text5.678);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "formattest";
    }
    
}
Copy after login


Note: There is only assignment and no formatting content in this code.

Change the content of the view formattest.jsp as follows:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextC//DTD HTML SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text.0SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text Transitional//EN" "http://www.wSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text.org/TR/htmlSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text/loose.dtd">
Copy after login
<meta><title>Insert title here</title>
    
    money:<br>
    <eval></eval><br>
    date:<br>
    <eval></eval><br>
    
Copy after login


Note: You need to add a reference here@taglib prefix="spring" uri="http://www.php.cn/" %>, and use spring:eval to bind the value to be displayed.

Run the test, change the browser language and refresh the page. You can still see the same effect as the screenshot in the first method, which proves that the annotation is valid.

The formatted display content ends here.

Note: I didn’t pay attention to the sample codes in the first SpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and TextSpringMVC Learning Series (7) Detailed Explanation of Formatted Display Graphics and Text articles before. I don’t know why the package and uploaded at that time did not have a .project project file. As a result, after downloading, it could not be directly imported into eclipse to run, and the virtual machine was I deleted it, and there is no backup of these sample codes, but the code files are still there, so you can create a new Dynamic Web Project and import the corresponding configuration files, controllers and views. I apologize for the inconvenience caused to everyone.

The above is the detailed explanation of the graphic display of formatted display in SpringMVC learning series (7). For more related content, please pay attention to the PHP Chinese website ( www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template