不喜勿噴!!!css
第一步 :html
package com.sso.util;java
public class HttpAgentUtil {
private final static String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" }; //定義移動端請求的全部可能類型
/**
* 判斷User-Agent 是否是來自於手機
* @param ua
* @return
*/
public static boolean checkAgentIsMobile(String ua) {
boolean flag = false;
if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
// 排除 蘋果桌面系統
if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
for (String item : agent) {
if (ua.contains(item)) {
flag = true;
break;
}
}
}
}
return flag;
}
}spring
第二步:服務器
package com.sso.config;jsp
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;ide
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;性能
import org.springframework.stereotype.Component;url
import com.sso.entity.User;
import com.sso.util.HttpAgentUtil;spa
@Component
@WebFilter("/*")
public class LoginFiter implements Filter{
/*實例化一個靜態的集合(這裏能夠改用map集合,提升性能,每次過濾能夠不用for匹配)*/
private static List<String> urls = new ArrayList<>();
//靜態代碼塊中向集合中存放全部能夠放行的請求或網頁地址(不用帳號密碼便可訪問)
static {
urls.add("/login");
urls.add("/login.html");
urls.add("/css");
urls.add("/js");
urls.add("/register");
urls.add("/userRegister.html");
urls.add("forgetPassword.html");
urls.add("findpwd.jsp");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
/**
* 攔截請求,看看用戶是否登錄,若是沒有登錄,
* 則跳轉回登陸頁面,不然就放行
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
/*注意:ServletRequest是HttpServletRequest父接口,所以須要強轉
一樣,ServletResponse是HttpServletResponse父接口,所以須要強轉*/
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
String ua = req.getHeader("User-Agent");
/*獲得當前頁面所在目錄下全名稱*/
String urlPattern=req.getServletPath();
/*獲得頁面所在服務器的絕對路徑*/
String path = req.getRequestURI();
for (String url : urls) {
if(url.equals(urlPattern) || path.contains(url)) {
chain.doFilter(request, response);
//防止重複響應
return;
}
}
//若是username爲null,表示沒有登陸
if(req.getSession().getAttribute("username")==null) {
if(HttpAgentUtil.checkAgentIsMobile(ua)){
res.sendRedirect("/sso-client/mobile/public/login.html");
}else {
res.sendRedirect("/sso-client/login.jsp");
}
}else {
//放行
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
第三步:
剩下的手機端頁面直接請求後臺功能便可