跳转H5手机端

package com.mes.interceptor;

import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mes.utils.DateJsonValueProcessor;

public class ViewInterceptor extends HandlerInterceptorAdapter{
	private static final String Default_DateFormat = "yyyy-MM-dd HH:mm:ss";//默认时间格式
	private Logger logger = Logger.getLogger(ViewInterceptor.class);
	private String mobileViewPrefix;
	
	/**
	 * 拦截器,跳转到页面前的拦截,功能有:
	 *  1. 当是手机访问时,在访问地址前加mobileViewPrefix,实现手机浏览时跳转到H5页面
	 *  2. 当是Ajax请求时,将ModelAndView中的Model转换为JSON字符串,实现手机分页查询时的滑动效果
	 * 
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		boolean isMobile = isMobileDevice(request.getHeader("user-agent"));//取访问设备类型
		String requestType = request.getHeader("X-Requested-With");//取访问类型 (Ajax or http)
		if (isMobile && modelAndView != null) {//手机浏览时跳转到h5页面
			String view = modelAndView.getViewName();
			if (view != null) {
				view = mobileViewPrefix + view;
				modelAndView.setViewName(view);
			}
		}
		
		if(requestType != null && "XMLHttpRequest".equals(requestType) && modelAndView != null){//Ajax请求 则返回json字符串 (分页时使用)
			PrintWriter out = getPrintWriter(response);
			try {
				Map<String, Object> model = modelAndView.getModel();
				String result = "";
				if (model != null) {
					result = JSONObject.fromObject(model, convertJsonConfigDate(Default_DateFormat)).toString();
				}
				out.print(result);
				modelAndView = null;
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				out.close();
			}
        } 
		super.postHandle(request, response, handler, modelAndView);
	}

	
	/**
	 * 取访问设备类型
	 * 
	 * @param requestHeader
	 * @return isMobileDevice
	 */
	public static boolean isMobileDevice(String requestHeader) {
		String[] deviceArray = new String[] { "iphone", "android", "phone", "mobile", "wap", "netfront", "java", "opera mobi",
                                            "opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry", "dopod",
                                            "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma",
                                            "docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos",
                                            "techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem",
                                            "wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos",
                                            "pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320",
                                            "240x320", "176x220", "w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac",
                                            "blaz", "brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs",
                                            "kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi",
                                            "mot-", "moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port",
                                            "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem",
                                            "smal", "smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v",
                                            "voda", "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-",
                                            "Googlebot-Mobile" };
		if (requestHeader == null)
			return false;
		requestHeader = requestHeader.toLowerCase();
		for (int i = 0; i < deviceArray.length; i++) {
			if (requestHeader.indexOf(deviceArray[i]) > 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 转换JsonConfig中的日期格式
	 * 
	 * @param dateformat
	 * @return JsonConfig
	 * @throws Exception
	 */
	public static JsonConfig convertJsonConfigDate(String dateformat) throws Exception {
		dateformat = dateformat.isEmpty() ? "yyyy-MM-dd HH:mm:ss" : dateformat;
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor(dateformat));
		return config;
	}
	
	/**
	 * 获取PrintWriter
	 * 
	 * @param response
	 * @param logger
	 * @param logmsg
	 * @return PrintWriter
	 * @throws Exception
	 */
	public static PrintWriter getPrintWriter(HttpServletResponse response) throws Exception {
		if (response != null) {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			return response.getWriter();
		}
		return null;
	}
	
	public String getMobileViewPrefix() {
		return mobileViewPrefix;
	}


	public void setMobileViewPrefix(String mobileViewPrefix) {
		this.mobileViewPrefix = mobileViewPrefix;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值