logo
down
shadow

Obtaining a Spring LocalResolver via RequestContext vs. via Injection?


Obtaining a Spring LocalResolver via RequestContext vs. via Injection?

By : Ahsan Sohail
Date : November 22 2020, 12:01 PM
wish helps you I don't think there are any pitfalls.
The RequestContextUtils.getLocaleResolver(HttpServletRequest) is implemented as
code :
public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
    return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}
private void initLocaleResolver(ApplicationContext context) {
    try {
        this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Using LocaleResolver [" + this.localeResolver + "]");
        }
    }
    catch (NoSuchBeanDefinitionException ex) {
        // We need to use the default.
        this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME +
                    "': using default [" + this.localeResolver + "]");
        }
    }
}
[...]
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
[...]


Share : facebook icon twitter icon
Obtaining a RequestContext for a templatetag included on every page

Obtaining a RequestContext for a templatetag included on every page


By : Jungho Lee
Date : March 29 2020, 07:55 AM
wish helps you All though there may be some workarounds, the best practice is definitely to add the RequestContext everywhere. This has advantages for other middlewares as well.
But there is also a legacy method, that will be removed in Django 1.4 that does not require you to change all your views. I would recommend against it unless you don't have much option.
How to access Spring RequestContext from a Freemarker TemplateDirectiveModel

How to access Spring RequestContext from a Freemarker TemplateDirectiveModel


By : user3116831
Date : March 29 2020, 07:55 AM
I wish this helpful for you You could subclass FreeMarkerConfigurer, overriding its postProcessConfiguration(Configuration config)method. Your implementation would just put a request-aware dependency in the configuration, as a shared variable for example (as preconised by the FM documentation).
Should do the trick, Spring-style...
Convert Spring field injection to constructor injection (IntelliJ IDEA)?

Convert Spring field injection to constructor injection (IntelliJ IDEA)?


By : Root Arivu Arasan
Date : March 29 2020, 07:55 AM
like below fixes the issue Yes, it's now implemented in IntelliJ IDEA.
1) Place your cursor on one of the @Autowired annotation.
code :
class MyComponent {

  @Inject MyCollaborator collaborator;

  public void myBusinessMethod() {
    collaborator.doSomething(); // -> NullPointerException   
  } 
}   
class MyComponent {

  private final MyCollaborator collaborator;

  @Inject
  public MyComponent(MyCollaborator collaborator) {
    Assert.notNull(collaborator, "MyCollaborator must not be null!");
    this.collaborator = collaborator;
  }

  public void myBusinessMethod() {
    collaborator.doSomething(); // -> safe   
  }
}
Spring LocalResolver based on query parameter 'lang=en'?

Spring LocalResolver based on query parameter 'lang=en'?


By : user1633843
Date : March 29 2020, 07:55 AM
I hope this helps you . The solution is probably as follows. Still I find the setup very counterintuitive. Especially I would have expected that:
the LocaleChangeInterceptor registers itself, but does not and have to call addInterceptors() explicit the spring.mvc.locale parameter is still set into the custom LocaleResolver, but does not and have to override manually from WebMvcProperties
code :
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
   @Bean
   public LocaleChangeInterceptor localeChangeInterceptor() {
       LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
       lci.setParamName("lang");
       return lci;
   }

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(localeChangeInterceptor());
   }

   @Bean
   public AcceptHeaderLocaleResolver localeResolver(WebMvcProperties mvcProperties) {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver() {
            @Override
            public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
                LocaleContextHolder.setLocale(locale);
            }
        };

        localeResolver.setDefaultLocale(mvcProperties.getLocale());
        return localeResolver;
    }
}
@Configuration
public class AppConfig implements WebMvcConfigurer {
   @Bean
   public AcceptHeaderLocaleResolver localeResolver(WebMvcProperties mvcProperties) {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver() {
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            String locale = request.getParameter("lang");
            return locale != null
                    ? org.springframework.util.StringUtils.parseLocaleString(locale)
                    : super.resolveLocale(request);
        }
        };

        localeResolver.setDefaultLocale(mvcProperties.getLocale());
        return localeResolver;
    }
}
EJB3 - obtaining bean via injection vs lookup - what are the differences, implications, gotchas?

EJB3 - obtaining bean via injection vs lookup - what are the differences, implications, gotchas?


By : user3836600
Date : March 29 2020, 07:55 AM
should help you out Both achieve the same result. It's more a matter of coupling. With annotation, you achieve loose coupling and it's easier to mock and test. With direct lookup, you depend on the initial context which may be unconvenient sometimes.
IMHO lookup does not work everywhere. For instance in Glassfish, a lookup on a local EJB from a POJO will work only if has been "imported" previously with @EJBs(...) on one of the session beans that uses the POJO. See this discussion. You need to understand the difference between the local and global JNDI for that.
Related Posts Related Posts :
  • Java Application Client Freezed with an JNIWrapper exception
  • How do i make sure that the ID of object im adding to array doesn't exist without getting nullpointerexception?
  • Code Coverage for every (different) input data
  • Is there a function in java which helps to format and return the formatted date as output?
  • How to reuse Android-Handler after removing callbacks
  • What's wrong with this solution of coin change problem?
  • Showing error while inserting User in room database
  • Feign : file upload configuration
  • How to differentiate row name by column heading, if there are multiple rows available
  • Change behavior without modifying base class
  • Why I have Permission denied on a file located in /data/user_de/
  • Calculate date range and return true
  • How to draw multiple points on imageview in android java
  • How to display ListView in Reverse Order (Latest First on Top)?
  • separate the file in fileinputstream input and insert the data into oracle tables
  • How to append a column of data to the end of text file
  • Return ArrayList item instead of boolean
  • Remove few elements from a Map of String to List for a specific key
  • Load more not working after swipe to refresh
  • Does a 'z' in a datetime String have different outputs in different locales?
  • What I have to modifiy for the 64-bit requirement?
  • Updating and deleting from DB using JpaRepository
  • Incompatible types with new class?
  • How to convert nested for loop with extra command to java stream
  • Set cookies on successful OAuth2 Authentication in Spring Security OAuth2 implementation
  • Groovy - Regex match the string with last char numbers
  • Problem when splitting an item from array list into a string array
  • Check link to know if it is image or not in android/java
  • Scala JSR223 script using JMeter/Java context
  • I executed selenium code but an error is appearing
  • Why are WebMvcConfigurer override methods not working?
  • JPA Criteria Specification for ManyToMany
  • Mongodb Timestamp Output Format returns "$numberLong" Object when I want to get the unix time in millis
  • Is SecureRandom.ints() secure?
  • Using advanced search operators in sending query to saerch engine using restful API
  • How I can get image Uri from gallery for a long time?
  • How to send List value in Request Body to Rest Api
  • How to get the processing kafka topic name dynamically in Flink Kafka Consumer?
  • How to pass function as parameter from java to kotlin method?
  • Java SWT - Adding buttons to shell
  • How "site" can be input for the viewer? What is "site" in Eclipse API?
  • "unreported exception IOException; must be caught or declared to be thrown". Have a look on the coding
  • Google Anlytics in Java: AnalyticsService "application name"
  • how to handle error when there is no coordinate to show in arraylist?
  • When should I use Factory<T> instead of Provider<T>
  • Why is assigning 'int constant -> byte variable' valid, but 'long constant -> int variable' is not?
  • Adding Service layer to Web APP to display DB contents on a jsp
  • How to fix java.awt.HeadlessException in Jenkins on Linux
  • Calling custom mongoDB query with spring data fails
  • Reusing visual class created with WindowBuilderPro
  • Is it allowed to have any logging on Android Public release?
  • Cannot pass java.lang.long to com.jacob.activeX.ActiveXComponent.invoke
  • Is initialization of objects Thread Safe in Java
  • Save as java file
  • JasperReports: filling a report throws an exception “TargetInvocationException”
  • How to insert about 500.000 data rows in table efficiently
  • Android Soundboard only one sound at a time
  • Inner forEach in forEach jstl error
  • Finding the key of HashMap which holds the lowest integer value
  • Time Difference with UTC java
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org