Search code examples
javaspringspring-mvcspring-mobile

How can I use view resolver to return mobile or normal view?


I have a web app and I want add the mobile version to it..

So I followed this guide to add spring-mobile, but I can't get my mobile views..

I don't want add in every controller's methods this piece of code:

if (device.isMobile()) {
  return "mobile/myPage.jspx";
} else if (device.isTablet()) {
  return "tablet/myPage.jspx";
} else {
  return "myPage.jspx";
}

So I'm trying to set a view-resolver to get the right page. I use Tiles and this is its configuration:

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>

And then I add this:

<bean class="org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver">
  <constructor-arg>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/views/" />
      <property name="suffix" value=".jsp" />
    </bean>
  </constructor-arg>
  <property name="tabletPrefix" value="tablet/" />
</bean>

But my we-app returns only /myPage.jspx and never /mobile or /tablet pages.

How can I do?

Thank you!


Solution

  • That isn't going to work. The UrlBasedViewResolver always returns a view regardless the fact if it exists or not. Also your UrlBasedViewResolver is always consulted first basically rendering your LiteDeviceDelegatingViewResolver useless.

    You also have to let your mobile views use Tiles and make sure that the configured prefix leads to a modified view. I would also suggest to use the TilesViewResolver convenience subclass, save you some XML.

    <bean class="org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver">
        <constructor-arg>
            <bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver" />
        </constructor-arg>
        <property name="mobilePrefix" value="mobile/" />
        <property name="tabletPrefix" value="tablet/" />
    </bean>
    

    And ofcourse remove your other configured ViewResolver.