JSP中的Facebook Connect示例(tomcat)

JSP中的Facebook Connect示例(tomcat),第1张

JSP中的Facebook Connect示例(tomcat)

这是我使用的servlet解决方案。只需稍作调整,您就可以使用简单的用户名-密码格式在任何JSP中使用它。无需Javascript
!!!至于地址和电话号码,请阅读以下内容:http :
//developers.facebook.com/blog/post/447

FBAuthServlet
public class FBAuthServlet extends HttpServlet {private static final Logger log = Logger.getLogger(FBAuthServlet.class);private static final long serialVersionUID = 1L;private UserService userService = //here goes your user service implementationpublic FBAuthServlet() {    super();}public void destroy() {    super.destroy(); // Just puts "destroy" string in log    // Put your pre here}public void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    HttpServletRequest req = (HttpServletRequest) request;    HttpServletResponse res = (HttpServletResponse) response;    if ("y".equals(request.getParameter("FacebookLogin"))) {        response.sendRedirect(FaceBookConfig.getLoginRedirectURL());        return;    }    String pre = req.getParameter("pre");    if (StringUtil.isNotBlankStr(pre)) {        String authURL = FaceBookConfig.getAuthURL(pre);        URL url = new URL(authURL);        try { String result = readURL(url); String accessToken = null; Integer expires = null; String[] pairs = result.split("&"); for (String pair : pairs) {     String[] kv = pair.split("=");     if (kv.length != 2) {         res.sendRedirect(FaceBookConfig.MAINURL);     } else {         if (kv[0].equals("access_token")) {  accessToken = kv[1];         }         if (kv[0].equals("expires")) {  expires = Integer.valueOf(kv[1]);         }     } } if (accessToken != null && expires != null) {     User user = authFacebookLogin(accessToken, request.getRemoteAddr());     if (user != null && user.getFacebookId() != null) {         //forward to spring security filter chain         res.sendRedirect(FaceBookConfig.MAINURL + "/j_spring_security_check?j_username=" + user.getEmail() + "&FaceBookId=" + user.getFacebookId());     } else if (user != null && StringUtil.isNullOrBlank(user.getFacebookId())) {         res.sendRedirect(FaceBookConfig.MAINURL + "/login.html?login_error=You are not Registered By Facebook Connect");     } else {         res.sendRedirect(FaceBookConfig.MAINURL);     } }        } catch (Exception e) { e.printStackTrace(); res.sendRedirect(FaceBookConfig.MAINURL);        }    }}public void doPost(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    doGet(request, response);}public void init() throws ServletException {}private String readURL(URL url) throws IOException {    ByteArrayOutputStream baos = new ByteArrayOutputStream();    InputStream is = url.openStream();    int r;    while ((r = is.read()) != -1) {        baos.write(r);    }    return new String(baos.toByteArray());}private User authFacebookLogin(String accessToken, String ip) {    try {        String content = IOUtil.urlToString(new URL("https://graph.facebook.com/me?access_token=" + accessToken));        JSonObject resp = new JSonObject(content);        String facebookid = resp.getString("id");        String firstName = resp.getString("first_name");        String lastName = resp.getString("last_name");        String email = resp.getString("email");        log.info("Facebook response: " + content);        CreateUserRequestCommand comm = new CreateUserRequestCommand();        comm.setEmail(email);        comm.setFacebookId(facebookid);        comm.setFirst(StringAndDateUtils.safeChar(firstName));        comm.setLast(StringAndDateUtils.safeChar(lastName));        //if success login        if (userService.getUserByEmail(email) == null) { //if first time login User u = userService.createUser(comm, ip); return u;        } else {//if existed User existedUser = userService.getUserByEmail(email); return existedUser;        }    } catch (Throwable ex) {        ex.printStackTrace();    }    return null;}}
FBEnableServlet
public class FBEnableServlet extends HttpServlet {private static final long serialVersionUID = 1L;private UserService userService = (UserService) ServiceLocator.getContext().getBean("userService");public FBEnableServlet() {    super();}public void destroy() {    super.destroy(); // Just puts "destroy" string in log    // Put your pre here}public void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    HttpServletRequest req = (HttpServletRequest) request;    HttpServletResponse res = (HttpServletResponse) response;    if ("y".equals(request.getParameter("EnableFacebookConnect"))) {        response.sendRedirect(FaceBookConfig.getEnableRedirectURL());        return;    }    String pre = req.getParameter("pre");    if (StringUtil.isNotBlankStr(pre)) {        String authURL = FaceBookConfig.getEnableAuthURL(pre);        URL url = new URL(authURL);        try { String result = readURL(url); String accessToken = null; Integer expires = null; String[] pairs = result.split("&"); for (String pair : pairs) {     String[] kv = pair.split("=");     if (kv.length != 2) {         res.sendRedirect(FaceBookConfig.MAINURL);     } else {         if (kv[0].equals("access_token")) {  accessToken = kv[1];         }         if (kv[0].equals("expires")) {  expires = Integer.valueOf(kv[1]);         }     } } if (accessToken != null && expires != null) {     User user = authFacebookLogin(accessToken, request.getRemoteAddr());     String loginedEmail = "";     try {         loginedEmail = SecurityContextHolder.getContext().getAuthentication().getName();     } catch (Exception ex) {     }     System.out.println("Logined email = " + loginedEmail);     System.out.println("Facebook Login email = " + user.getEmail());     if (user != null && user.getFacebookId() != null && user.getEmail().equals(loginedEmail)) {         userService.setFaceBookid(user.getFacebookId());         //forward to spring security filter chain         res.sendRedirect(FaceBookConfig.MAINURL + "/j_spring_security_check?j_username=" + user.getEmail() + "&FaceBookId=" + user.getFacebookId());     } else {         res.sendRedirect(FaceBookConfig.MAINURL + "/secure/myAccount.html?message=Please login Facebook with same Email,you Login with " + user.getEmail());     } }        } catch (Exception e) { e.printStackTrace(); res.sendRedirect(FaceBookConfig.MAINURL);        }    }}public void doPost(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    doGet(request, response);}public void init() throws ServletException {}private String readURL(URL url) throws IOException {    ByteArrayOutputStream baos = new ByteArrayOutputStream();    InputStream is = url.openStream();    int r;    while ((r = is.read()) != -1) {        baos.write(r);    }    return new String(baos.toByteArray());}private User authFacebookLogin(String accessToken, String ip) {    try {        String content = IOUtil.urlToString(new URL("https://graph.facebook.com/me?access_token=" + accessToken));        JSonObject resp = new JSonObject(content);        String facebookid = resp.getString("id");        String email = resp.getString("email");        User existedUser = userService.getUserByEmail(email);        if (existedUser == null) { return null;        } else { existedUser.setFacebookId(facebookid); return existedUser;        }    } catch (Throwable ex) {        ex.printStackTrace();    }    return null;}}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5123800.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存