Reputation: 1927
I have two folders inside my WEB-INF directory 1st is views
which has desktop website related template files and 2nd one mobile_views
has mobile website template. I am using WebConfiguration class file and define required @Bean
functions. Now I want to change the viewResolver.setPrefix(viewFolderName)
according to the request. If user hits the website from mobile so will set mobile_views
otherwise It will views
. So I am detecting the device browser and setting the viewFolderName
but seems to work only one time because WebConfiguration
class getting accessed when server starts, that's why I am facing this problem. Here is my code, please give me some solution for this.
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass( JstlView.class );
if(isRequestFromMobile()) viewResolver.setPrefix("/WEB-INF/mobile_views/");
else viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
private @Autowired HttpServletRequest request;
private boolean isRequestFromMobile() {
String userAgent = request.getHeader("User-Agent");
String httpAccept = request.getHeader("Accept");
UAgentInfo detector = new UAgentInfo(userAgent, httpAccept);
System.out.println("### User Agent: "+userAgent);
if (detector.detectMobileQuick()) {
return true;
}
return false;
}
Upvotes: 2
Views: 2895
Reputation: 64039
Take a look at this tutorial from Spring's site that depends on Spring Boot.
The meat is that you need to configure DeviceResolverHandlerInterceptor
and DeviceHandlerMethodArgumentResolver
.
Once that is done, you can use the controller method's Device argument to differentiate the handling depending on the device
A step further from that point would be to integrate LiteDeviceDelegatingViewResolver
(provided by Spring Mobile) in the following manner:
@Bean
public LiteDeviceDelegatingViewResolver liteDeviceAwareViewResolver() {
InternalResourceViewResolver delegate =
new InternalResourceViewResolver();
delegate.setPrefix("/WEB-INF/views/");
delegate.setSuffix(".jsp");
LiteDeviceDelegatingViewResolver resolver =
new LiteDeviceDelegatingViewResolver(delegate);
resolver.setMobilePrefix("mobile/");
resolver.setTabletPrefix("tablet/");
return resolver;
}
Upvotes: 2