Does someone had this problem:
I need to configure spring to recognize locale based date and number format, i.e. the following user behavior should be valid:
User select language to EN, then the number format 1.23 should be valid, spring mvc will accept this format and no valid error triggered. User can also change the date with date format MM/dd/yyyy and no valid error raised, user can post this form.
User select language to DE, then the number format 1,23 should bevalid, spring mvc will accept this format and no valid error triggered. User can also change the date with date format dd.MM.yyyy and no valid error triggerd. User can post this form.
I'v tried to use #DateTimeFormat(pattern="#{messageSource['date_format']}"),(I have date_format defined in messages_(locale).properties) but seems spring doesn't support this yet, see JIRA ISSUE
Does someone has the similar problem and got a solution.
Does it help to write my own converter, and register it in org.springframework.format.support.FormattingConversionServiceFactoryBean? I need some kind of request based converter
Since nobody answers my question, I just post one of my solution to solve this problem, it could help others:
I had a request scoped bean, which resolves locale using: RequestContextUtils.getLocale(request); request can be autowired to the request scoped class(NOTICE, it works only with field injection, not with construction or setter). In this class I get locale based date/number format.
In my controller (we have actually a abstractController). I have code like this:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new LocalizedDateEditor(formatHelper));
}
formatHelper is the request scoped bean. LocalizedDateEditor looks like this:
public class LocalizedDateEditor extends CustomDateEditor {
public LocalizedDateEditor(FormatHelper formatHelper) {
super(new SimpleDateFormat(formatHelper.getDefaultDateFormat()), true);
}
}
It just tell spring to use my dateFormat.
That's all.
Related
In a e-commerce application, I am translating all the entities for creating a receipt.
Sometimes, a product may have not been translated yet, in this case, I want to provide another message from the record in my database.
In a java spring boot 1.5.9 application, how can I tell if a translation message exists for a given message key in a given locale?
Use MessageSourceAccessor#getMessage to read the message for your desired locale.
The signature is
public String getMessage(String code, Locale locale)
throws NoSuchMessageException
If the message is not found with the provided locale, NoSuchMessageException will be thrown.
I was tasked with writing a test for a REST service by calling its endpoint with an HTTP request. One part of the HTTP request should be a date (to filter only items modified after that date). The problem is, that I cannot seem to properly pass the date into the HTTP request.
This is how the endpoint is defined in the Rest Controller:
#GetMapping("/{resourceType}/{application}")
public Map<String, Map<String, Map<String, Map<String, String>>>> findByTypeAndApplication(#PathVariable("resourceType") ResourceType type,
#PathVariable("application") String application,
#RequestParam(name = "modifiedAfter", required = false) #DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date modifiedAfter)
It is the "modifiedAfter" parameter that is giving me trouble. Trying to pass a date formatted according to the "pattern" does not appear to work for me. After parsing into URL, the request would look like this:
http://.../LANGTEXT/INTEGRATION-EXCEL-TEST?modifiedAfter=2019-06-11%2021%3A28%3A44
I also tried restassured.given to build the requests. I tried to pass the parameter in the address itself, as a param(), as a queryParam(), and as a formParam(). I tried to pass it both as a formatted string (as per the pattern), and as a Date object. Nothing seems to work.
I cannot change the controller itself (including the date format), so I need to properly pass the date in the HTTP request.
I'd be grateful for any advice.
Thanks, Petr
On server side, spring does this automatically. You don't need specify date pattern.
In Spring MVC, I can use PropertyEditor(Converter) or WebArgumentResolver(HandlerMethodArgumentResolver) to make customized command and form-backing objects. I'm puzzled which one should I use and what's the difference between them? Thanks a lot!
p.s. I know Converter and HandlerMethodArgumentResolver is recommended now. I've read the posts below:
Spring MVC type conversion : PropertyEditor or Converter?
Upgrading to spring-3.1 seems to break my CustomWebArgumentResolver
A converter simply converts between two different types. An HttpMessageConverter converts a request message having a defined media type to an instance of a defined class. Converters are usually called by argument resolvers.
An argument resolver provides a value for an argument. E.g. there is a resolver that creates the value based an a request parameter (#RequestParam) or one that converts the request body (#RequestBody). Both use converters.
But the value doesn't have to be related to the request. You could create a resolver that returns the current time, something like
public void foo(#CurrentTime Date) {
I'm pretty new to grails and I'm sure this has been asked multiple times. I have an application which I'm developing in grails. In my service, I make an entry into multiple tables. If one of them fails with a mysql unique constraint exception, I get an error as part of domainInstance.errors object. How do I parse this to return appropriate error code to my controller.
Normally in spring, I was generally adding an exception interceptor for controller to take care of this. Whats the preferred way to do it in grails.
When a validated domain object has validation errors they are stored under domainObject.errors, as an implementation of the Spring Errors interface. To render the errors for a field of this object in a GSP, you typically use something like:
<g:hasErrors bean="${book}" field="title">
<div class="errors">
<g:renderErrors bean="${book}" field="title" as="list" />
</div>
</g:hasErrors>
The exact message that is displayed is resolved from the message*.properties files. If you want to get these messages in a controller instead, do this:
class MyController {
MessageSource messageSource
LocaleResolver localeResolver
def myAction(Book book) {
Locale locale = localeResolver.resolveLocale(request)
if (!book.validate()) {
List allErrorMessages = book.errors.allErrors.collect {
messageSource.getMessage(it, locale)
}
// print all error messages
println allErrorMessages
}
}
}
let's assume we have a signup form. When some input of the form is changed, I want to validate its value on the fly by using the ajax call to the server. Is there a chance to validate only some particular property of the bean by using the JSR 303 validation?
The signup form handler validates the received bean just fine, but I want to find out the way to check the property before submit the whole bean.
The straight forward approach is just to create a server-side method to receive the property name and value and based on the name check the value, but I hope there is a way to use already defined constraints for the bean.
For example, the user entered the email address and moved forward to the next property. The client makes a call and the server method checks if the provided email is already exist. If so, it returns an error and I do show it up on the client side. I believe it may make the signup process more flexible and user friendly
Any comments are really appreciated.
The jsr-303 Validator does have a method right on it to validate just one property:
<T> java.util.Set<ConstraintViolation<T>> validateProperty(T object,
java.lang.String propertyName,
java.lang.Class<?>... groups)
You just need to inject the validator so that you can use it directly, rather than relying on Spring to call it automatically via putting #Valid on a method parameter.