1. What is the main job of a Formatter in Spring MVC?
Why: A Formatter works in both directions. It turns an object into a String to show it, and it turns a String back into an object when data comes in.
2. Which two interfaces does the Spring Formatter interface extend?
Why: Formatter extends Printer (object to text) and Parser (text to object). So a formatter has both abilities.
3. Which method of a Formatter turns an object into text?
Why: The print() method comes from Printer. It takes an object and returns a String.
4. Which method of a Formatter turns text into an object?
Why: The parse() method comes from Parser. It takes a String and returns an object.
5. In Formatter<T>, what does the type T stand for?
Why: T is the Java type the formatter works with. For example, a Formatter<Address> prints and parses Address objects.
6. Why do the print() and parse() methods receive a Locale parameter?
Why: The Locale lets a formatter follow local rules, such as how dates or numbers are written in different regions.
7. In which package is the Formatter interface found?
Why: The Formatter, Printer and Parser interfaces are in the org.springframework.format package.
8. You want to register a custom formatter for the whole web application. Which method name completes the code?
@EnableWebMvc
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void ______(FormatterRegistry registry) {
registry.addFormatter(new MyFormatter());
}
}
Why: To register formatters, you override addFormatters(FormatterRegistry) from WebMvcConfigurer.
9. Which method of FormatterRegistry is used to add a custom formatter?
Why: FormatterRegistry.addFormatter() registers a formatter so Spring MVC can use it.
10. What is the scope of a formatter that is registered with addFormatters()?
Why: A formatter registered in WebMvcConfigurer is global. All controllers and requests in the application can use it.
11. You want to customize a formatter only for a specific controller or request. Which approach can you use?
Why: An @InitBinder method lets you set up formatters for a controller or request. This is useful when you do not want a global setting.
12. Which checked exception can the parse() method of a Formatter throw?
Why: The parse() method declares java.text.ParseException. It is used when the text cannot be converted to an object.
13. When does Spring MVC call the parse() method of a registered formatter?
Why: Spring calls parse() during data binding. For example, a text value from a form is converted into the object type that the formatter supports.
14. When does Spring MVC use the print() method of a registered formatter?
Why: Spring uses print() to get the text form of an object, so it can be displayed to the user.
15. How can one formatter class support more than one output style?
Why: A formatter is a normal Java class. You can add fields such as a style setting, change its value, and then register the formatter.