What a boring day, while I was dreaming on my desk, something has caught my attention. I realize that in most of the time, my web application was run on desktop platform, and never know what would happen if I run the it on mobile platform? I was thinking this could be a disaster for user. But how? Could I do the validation checking in controller bean? Just like this:
If mobile device then render mobile site otherwise render desktop site.
But in reality, what I got from the Internet majority are done using
JavaScript, some use
CSS to accomplished the task. But this doesn't help because mine technology used was JSF and J2EE stuff. Thus I would use
Filter for my case. See my action on following content:
package org.huahsin;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(filterName="MyFilter", urlPatterns={"/pages/*", "*.xhtml"})
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
// redirect to mobile version
if( httpServletRequest.getHeader("User-Agent").indexOf("Mobile") != -1 ) {
...
...
}
else {
chain.doFilter(request, response); // forward to original request
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
This code will easily know where does the request come from. I'm so curious to know what is actually hiding in
User-Agent? Did a quick diagnose on it and found the following string will be retrieve when the site was render on desktop browser:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
And this is the string I got if I render the site on iPad:
Mozilla/5.0 (iPad; CPU OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12F69 Safari/600.1.4
No comments:
Post a Comment