분류 전체보기

spring social

2014. 2. 12. 16:04
반응형

spring social facebook

-로그인/개인프로필/친구정보 불러오기 테스트.

스프링 소셜 라이브러리를 사용하기 위해 먼저 maven 프로젝트를 생성.

그 전에 facebook 개발자센터에서 appId, secretKey를 발급 받고, 테스트할 URL을 등록이 필요하다. 

-pom.xml


	org.springframework.social
	spring-social-core
	1.0.2.RELEASE



	org.springframework.social
	spring-social-web
	1.0.2.RELEASE




	org.springframework.social
	spring-social-facebook
	1.0.2.RELEASE


	org.springframework.social
	spring-social-facebook-web
	1.0.2.RELEASE

-property 
#facebook appId, secretKey 
facebook.appId=575657749192479 
facebook.secretKey=df3ebe71b7eee8771c6fee1e0124f9ec 
callback.host=http://localhost:8080 

-SocialController.java
@Controller
@RequestMapping("/facebook")
@PropertySource("classpath:/setting.properties")
public class SocialController {
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
		
	@Resource
	private Environment environment;
        
	 /**
	 * index
	 * 메인
	 * @param model
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public String index(HttpSession session, Model model){
		//facebook info setting
	    Facebook facebook = new FacebookTemplate((String)session.getAttribute("ACCESS_TOKEN"));
	    FacebookProfile profile = facebook.userOperations().getUserProfile();
	    //List friends = facebook.friendOperations().getFriendIds();
	  	//byte[] profiles = facebook.userOperations().getUserProfileImage();
	    
	    String myId = profile.getId();
		String myName = profile.getName();
		String myEmail = profile.getEmail();
		String myGender = profile.getGender();
		
		Map profileInfo = new HashMap();
		profileInfo.put("myId", myId);
		profileInfo.put("myName", myName);
		profileInfo.put("myEmail", myEmail);
		profileInfo.put("myGender", myGender);
		
		logger.info("myId=>{}", myId);
		
		model.addAttribute("profileInfo", profileInfo);
		
		return "index";
	}
	
	/**
	 * freiend Info search
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getFriendInfo")
	public String getFriendsInfo(HttpSession session, Model model){
		Facebook facebook = new FacebookTemplate((String)session.getAttribute("ACCESS_TOKEN"));
		List friends = facebook.friendOperations().getFriendIds();

		model.addAttribute("friendsList", friends);
		return "index";
	}
	
	/**
	 * facebookSignin
	 * 페이스북 로그인 팝업 호출
	 * @param response
	 * @param request
	 * @param model
	 * @return
	 * @scope user_about_me:사용자 본인 정보, publish_stream: 기본적인 쓰기권한, read_friendlists: 친구 목록       
	 * @throws Exception
	 */
	@RequestMapping(value="/facebookSignIn" , method = RequestMethod.GET)
	public String facebookSignin(HttpServletResponse response, HttpServletRequest request, Model model) throws Exception {
		logger.info("{}","facebookSignIn START");
		
        String callbackUrl = environment.getProperty("callback.host")+"/social/facebook/facebookAccessToken";
        String oauthUrl = "https://www.facebook.com/dialog/oauth?" +
                        "client_id="+ environment.getProperty("facebook.appId")+"&redirect_uri="+URLEncoder.encode(callbackUrl, "UTF-8")+
                        "&scope=user_about_me,publish_stream,read_friendlists,offline_access";
                        	
        model.addAttribute("oauthUrl", oauthUrl);
        return "home";
	}
	
	/**
	 * facebookAccessToken
	 * 페이스북 로그인 결과 리턴
	 * @param request
	 * @param model
	 * @param message
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value="/facebookAccessToken")
	public String getFacebookClientAccessToken(HttpServletRequest request, Model model, @RequestParam(value="message", defaultValue="" , required=false) String message, HttpServletResponse response) throws Exception {
		String code 			= request.getParameter("code");
		String errorReason 		= request.getParameter("error_reason");
		String errorDescription = request.getParameter("error_description");
		
		if(logger.isInfoEnabled()){
			logger.info("code => " +code);
			logger.info("errorReason code => " + errorReason);
			logger.info("errorDescription => " + errorDescription);
		}
		
		//facebook accessToken call
		requestAccesToken(request, code);
	    
	    return "callback";
	}
	
	/**
	 * facebook accessToken request
	 * 토큰값 받아옴
	 * @param request
	 * @param code
	 * @throws Exception
	 */
	public void requestAccesToken(HttpServletRequest request, String code) throws Exception{
		String accessToken = "";
		String result	   = "";

		String callbackUrl = environment.getProperty("callback.host")+"/social/facebook/facebookAccessToken";
		String url = "https://graph.facebook.com/oauth/access_token"+
	    		"?client_id="+environment.getProperty("facebook.appId")+
	    		"&client_secret="+environment.getProperty("facebook.secretKey")+
	    		"&redirect_uri="+URLEncoder.encode(callbackUrl, "UTF-8")+
	    		"&code="+code;
		
		//httpGet 통신
		HttpGet httpGet = new HttpGet(url);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		result = httpClient.execute(httpGet, new BasicResponseHandler());
		accessToken = result.split("&")[0].replaceFirst("access_token=", "");
		
		//토큰값 세션처리
	    setAccessToken(request, accessToken);
	}
	
	/**
	 * setAccessToken
	 * 토큰값 세션 저장
	 * @param request
	 * @param accessToken
	 * @throws Exception
	 */
	public void setAccessToken(HttpServletRequest request, String accessToken) throws Exception {
		request.getSession().setAttribute("ACCESS_TOKEN", accessToken);
		logger.info("ACCESS_TOKEN => " + request.getSession().getAttribute("ACCESS_TOKEN"));
	}
}
-home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>



	facebook 로그인 하기 Sample


Spring Social Facebook oAuth

 
-callback.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>



	facebook 로그인 하기 Sample


-index.jsp

본인정보

<이미지 태그="https://graph.facebook.com/${pInfo.myId}/picture">
myEmail: ${pInfo.myEmail}
myGender: ${pInfo.myGender}
myName: ${pInfo.myName}
myId: ${pInfo.myId}

친구정보 불러오기

<앵커 태그="${pageContext.request.contextPath}/facebook/getFriendInfo">조회
<이미지 태그="https://graph.facebook.com/${fList}/picture">${fList}


반응형

spring mvc 모델 생성

2014. 2. 11. 16:09
반응형
1. 뷰에 전달되는 모델 데이터 
@RequestMapping 매서드가 ModelAndView , Model , Map을 리턴하는 경우 이들에 담긴 모델 데이터가 뷰에 전달 된다. 또한 , 추가로 다음의 항목도 뷰에 함께 모델로 전달 된다. 
- 커맨드 객체 - @ModelAttribute 어노테이션이 적용된 매서드가 리턴한 객체 
- 매서드의 Map , Model , ModelMap 타입의 파라미터를 통해 설정된 모델 아래 코드는 다양한 방법으로 모델 데이터를 설정 하고 있다.
@Controller
public class GameSearchController {
   private SearchService searchService;

   @ModelAttribute("searchTypeList")  //리턴된 options가 searchTypeList로 뷰에 전달 된다.
   public List referenceSearchTypeList() {
      List options = new ArrayList();
      options.add(new SearchType(1,"전체"));
      options.add(new SearchType(2,"아이템"));
      options.add(new SearchType(3,"캐릭터"));
      return options;
   }

   @RequestMapping("/search/game.do");
   public ModelAndView search( @ModelAttribute("command") SearchCommand command ,
                                         ModelMap model) {
      String[] queryList = getPopularQueryList();
      model.addAttribute("popularQueryList" , queryList);  //뷰에 전달
      ModelAndView mav = new ModelAndView("search/game");
      SearchResult result = searchService.search(command);
      mav.addObject("searchResult" , result); //뷰에 전달
      return mav;
   }
} 
@ModelAttrubute 어노테이션이 적용된 referenceSearchTypeList()매서드가 리턴한 모델 객체는 "searchTypeList" 라는 이름으로 뷰에 전달 된다. 이들 모델 객체는 서로 다른 방법으로 생성 되었지만 , DispatcherServlet은 이들 모델 객체에 저장된 모델 데이터를 모두 뷰에 전달 한다.
${popularQuery}
검색 결과 : ${searchResult}
2-1. Map , Model , ModelMap을 통한 모델 설정 Map , Model , ModelMap을 이용하면 뷰에 전달할 모델을 생성할 수 있다. 1) 세가지 타입중 한가지를 파라미터로 전달 받는 방법
   
    @RequestMapping("/search1.do")
       public String search1(Map model) {
          model.put("result" , searchResult); //뷰에게 전달할 모델 데이터 추가
       }
2) Map과 Model을 리턴 하는 방법
      @RequestMapping("/search1.do")
      public Map search1() {
         HashMap model = new HashMap();
         model.put("result" , searchResult);
         return model;
      }
스프링은 org.springframework.ui.Model 인터페이스의 구현 클래스인 ExtendedModelMap 클래스를 동일한 패키지에 제공하고 있으므로 , ExtendedModelMap 클래스를 이용해서 모델을 설정 하면 된다. 
Map의 경우 많이 사용하는 java.util.HashMap클래스를 이용해서 모델을 설정 한다. 2-2. Model 인터페이스의 주요 매서드 org.springframework.ui.Model 인터페이스는 모델을 설정할 수 있도록 다음과 같은 매서드를 제공 하고 있다. Model addAttribute(String name , Object value) : value 객체를 name 이름으로 추가 한다. 
뷰 코드에서는 name으로 지정한 이름을 통해 value 사용 Model addAttribute(Object value) : value를 추가 한다. value 패키지 이름을 제외한 단순 클래스 이름을 모델 이름으로 사용 한다. 이때 첫글자는 소문자로 처리 한다. value가 배열이거나 컬렉션인 경우 첫번째 원소의 클래스 이름 뒤에 "List"를 붙인 걸 모델 이름으로 사용한다. 
이 경우에도 클래스 이름의 첫글자는 소문자로 처리 한다. 
Model addAllAttributes(Collectin values) : addAttribute(Object value) 매서드를 이용해서 컬렉션에 포함된 객체들을 차례대로 추가 한다. 
Model addAllAttributes(Map attributes) : Map에 포함된 <키,값>에 대해 키를 모델 이름으로 사용해서 값을 모델로 추가 한다. 
Model mergeAttributes(Map attributes) : Map에 포함된 <키,값>을 현재 모델에 추가 한다. 단 키와 동일한 이름을 갖는 모델 객체가 존재 하지 않는 경우에만 추가 된다. 
boolean containsAttributes(String name) : 지정한 이름의 모델 객체를 포함하고 있는 경우 true를 리턴 한다. 다음 코드는 컨트롤러 요청 처리 매서드에서 Model 타입의 파라미터를 이용해서 모델을 설정하는 예를 보여 주고 있다.
@RequestMapping("/search/game.do")
public String search(SearchCommand command , Model model) {
   model.addAttribute("searchResult" , result);
   model.addAttribute("searchTypeList" , searchTypeList);
}
 
컨트롤러 요청 처리 매서드에서 Model 타입을 리턴하고 싶다면 Model 인터페이스의 구현 클래스인 org.springframework.ui.ExtendedModelMap 클래스를 사용하면 된다.
@RequestMapping("/search.game.do")
public String search(SearchCommand) {
   Model = model = new ExtendedModelMap();
   model.addAttribute("searchResult" , result);
   return model;
}
2-3. ModelMap 클래스 org.springframework.ui.ModelMap 클래스는 Map의 구현 클래스로서 제공하는 , 컨트롤러 매서드의 파라미터를 통해서 전달 받는다. 
@RequestMapping("/search/game.do") public String search(SearchCommand command , ModelMap model) { model.addAttribute("result" , searchResult); } ModelMap 클래스가 제공하는 모델 설정 관련 매서드는 Model 인터페이스와 동일 하므로 추가 설명은 않는다.
3. ModelAndView를 통한 모델 설정
org.springframework.web.servlet.ModelAndView 클래스는 컨트롤러의 처리 결과를 보여줄 뷰와 뷰에 전달할 값을 저장하는 용도로 사용 된다.
setViewName(String viewName) 매서드를 이용하여 뷰 이름 설정 , addObject(String name , Object value) 매서드를 이용하여 뷰에 전달할 값을 추가 한다.

@RequestMapping("/search/game.do")
public ModelAndView search(SearchCommand command) {
   ModelAndView mav = new ModelAndView();
   mav.setViewName("search/game");
   mav.addObject("searchResult" ,searchResult);
   mav.addObject("searchTypeList" , typeList);
   return mav;
}
Map에 저장된 <키,값> 쌍 전체를 뷰에 전달하고 싶다면 addAllObjects(Map modelMap)매서드를 사용하면 된다. Map referenceMap = referenceData(); mav.addAllObjects(referenceMap); 생성자를 사용해서 뷰 이름과 Map을 전달할 수도 있다. 
Map referenceMap = referenceData(); return new ModelAndView("search/game" , referenceMap); 뷰에 전달할 객체가 한개 뿐이라면 생성자를 이용해서 코드 분량을 줄일 수 있다. 
return new ModelAndView("search/game" , " result" , searchResult); 


[kki.tistory.com 퍼옴]


반응형
반응형

jQuery 자식 팝업 창에서 부모창 컨트롤

$(opener.document).find("#Form").attr("action","index.do").submit();

자식창 -> 부모창으로 값 전달하기

opener.document.getElementById("id").value="value"; //dom 객체로 제어 

$("#id",opener.document).val("value"); // jQuery 방식 1 

$("input[name=imgFile]", parent.document.body).val() // 방식 2 

$(opener.document).find("#id").val("value"); //방식 3  

opener.location.href="javascript:fun();"; //일반적인 방법 

$(opener.location).attr("href","javascript:fun();"); //jQuery 이용
반응형

'Programming > Frontend' 카테고리의 다른 글

jQuery multi redio button valid check  (0) 2014.02.13
[ajax] JSONP CROSS SITE 응답 받기  (0) 2014.02.12
jquery hover 효과  (0) 2013.12.20
jQuery.noConflict() alias 사용  (0) 2013.03.24
jQuery Selector 정리  (0) 2013.03.24
반응형
보통은 1Byte 문자열 타입을 쓰지만
다중언어 지원 시스템에선 2Byte를 사용한다.
 
│ MsSQL │ Oracle │
* 1byte
│ char  │char   │ -> 고정 문자열 : 한글 2자리, 영문 1자리
│ varchar│varchar2 │ -> 비고정 문자열 : 한글 2자리, 영문 1자리
 
*2Byte : 유니코드 문자열
│ nchar  │nchar  │ -> 고정 문자열 : 한글 1자리, 영문 1자리 , 기타언어 1자리

│ nvarchar│nvarchar2│ -> 비고정 문자열 : 한글 1자리, 영문 1자리 , 기타언어 1자리
반응형

올바른 eqals() 사용법

2014. 2. 7. 12:51
반응형
  • java에서 빈번하게 상용하는 비교함수 equals()

변수.equals(비교문자열)
이 형태는 변수의 값이 절대적으로 null이 나오지 않을 경우에는 상관이 없다
하지만 requst.getParameter()를 사용해서 변수의 값을 초기화 한다거나 변수의 값이 null 이 들어올 수 있다.
변수.equals(비교문자열) 이 형태에서 변수에 null 이 들어오게 되면 Exception 이 발생 한다.

비교문자열.equals(변수)
형태로 문자열을 비교한다면 변수에 null 이 들어와도 Exception 이 발생하지 않는다.(false 출력됨)
이유는 문자열을 비교할때 주체가 되는 대상이 달라진다.
변수.equals(비교문자열) : 변수가 주체가 되어서 문자열 비교
비교문자열.equals(변수) : 비교문자열이 주체가 되어서 문자열 비교

  
public void eqals(){
    String testVal = null;
    String result = "";
        
    /* Exception 발생 */
    //if( !(testVal.equals("")) ) result = "1";
   
    /* 정상 */
    if( !("".equals(testVal)) ) result = "2";
}

 

반응형

+ Recent posts

반응형