오....간만에 초간단 시리즈-_-;
그냥 넷빈즈6.5가 새로 나와서 Hibernate도 공부해볼 겸 해서 삽질을 좀 해봤습니다. Hibernate를 공부하고 있는데, 왜이렇게 어렵죠ㅠ 아직도 잘 모르겠습니다. 좋은 자료가 있으시면 댓글로 좀 알려주세요 ㅠ(굽신굽신 ㅠ)

넷빈즈6.5 JDK6U10환경에서 해봤습니다.

File New Project -> Java -> Java Application 선택.
Project Name은 WondergirlsHibernate로 하고 Finish!(원더걸스를 예제로 해야 접근성이 좋은..-_-)

Mysql에다가 DB를 만들어봅시다.
첫번째 테이블은 wondergirls에 대한 정보를 나타냅니다. 이름과 나이가 있습니다.
[code]CREATE TABLE  `wondergirls`.`wondergirls` (
  `idx` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `age` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`idx`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `wondergirls` (`idx`,`name`,`age`) VALUES
 (1,'선예',20),
 (2,'선미',20),
 (3,'소희',17),
 (4,'예은',17),
 (5,'유빈',21);
[/code]
두번째 테이블은 과목점수를 나타냅니다. widx 칼럼이 wondergirls테이블의 idx와 FK로 연결되었습니다.
[code]CREATE TABLE  `wondergirls`.`score` (
  `idx` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `widx` int(10) unsigned NOT NULL,
  `korean` int(10) unsigned DEFAULT NULL,
  `math` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`idx`),
  KEY `FK_score_1` (`widx`),
  CONSTRAINT `FK_score_1` FOREIGN KEY (`widx`) REFERENCES `wondergirls` (`idx`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `score` (`idx`,`widx`,`korean`,`math`) VALUES
 (1,1,100,100),
 (2,2,90,90),
 (3,3,80,80),
 (4,4,70,70),
 (5,5,60,60);
[/code]
넷빈즈에 Mysql을 추가를 안하셨다면 추가를 하셔야합니다.
왼쪽에서 Projects탭 말고,  Services탭을 클릭합니다. Register Mysql를 클릭해서 정보를 입력하여 추가합니다. connect했을 때 db가 보인다면 추가가 잘 된 것입니다. start나 stop도 이곳에서 관리하려면 추가로 입력하시면 되는데, 입력안하고, 외부에서 실행하고 종료해도 상관 없더군요.

그러면 다시 Projects탭으로 돌아와서.....프로젝트이름에 대고, 오른쪽버튼 -> New -> Hibernate -> Hibernate Configuration File선택 -> Name and Location에서는 그냥 Next -> Database Connection은 방금 추가한 테이블이 있는 Mysql의 db를 선택합니다. Finish를 누르면 각종 설정화면이 나옵니다.
여기서 Optional Properties -> Configuration Properties에 add하고, hibernate.show_sql을 true로 설정한 것을 추가합니다. 이제 XML로 보면 이렇게 보일겁니다.
[code]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/wondergirls</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">mudchobo</property>
    <property name="hibernate.show_sql">true</property>
  </session-factory>
</hibernate-configuration>
[/code]
설정하기 편하게 되어있군요. 다 뭐하는 건지는 하나씩 해봐야 알 것 같아요 ㅠ 우선은 sql쿼리만 볼 수 있도록 하고-_-;

이제 HibernateUtil을 추가합니다. 설정파일을 통해 session을 가져오는 유틸인 듯 합니다.
Ctrl + N -> Hibernate -> HibernateUtil.java 선택.
Class Name은 New를 뺀 HibernateUtil, Package는 wondergirlshibernate.util로 합시다. Finish를 누르면 자동으로 생성됩니다.

이제 매핑파일을 가져옵시다.
Ctrl + N -> Hibernate -> Hibernate Mapping Files and POJOs from Database 선택.
Name and Location에서는 그냥 Next.
hibernate.cfg.xml이 자동으로 선택이 되는데, 거기에 방금 생성한 테이블이 있을 겁니다.
사용자 삽입 이미지
score를 추가하면 wondergirls는 따라옵니다. 서로 연결이 되어있어서 필요합니다. Next한다음에 Package에 wondergirlshibernate.entity로 하고 Finish를 클릭합니다.

이제 entity도 만들어졌으니, HQL을 테스트해볼 수 있습니다.
Source Packages -> default package -> hibernate.cfg.xml에 오른쪽버튼 클릭 후 Run HQL Query를 클릭하면 쿼리를 날릴 수 있습니다. 아래와 같이 날려봅시다.
[code]from Score[/code]
사용자 삽입 이미지
이렇게 결과를 볼 수 있습니다.
별 것도 없는데 글이 길어 지네-_-; 다음 글에-_-;

[NetBeans] 넷빈즈를 이용한 Hibernate 초간단 예제2 - 데이터가져오기.


참조글 : http://www.netbeans.org/kb/docs/java/hibernate-java-se.html
 
Posted by 머드초보
,
 
저번달에 선테크데이를 다녀왔을 때 거기서 강조한 넷빈즈가 드디어 6.5버전을 릴리즈했네요.
우선 상세히 살펴보지는 않았는데요. 릴리즈 정보를 보면 엄청나게 막강해졌네요.

http://www.netbeans.org/community/releases/65/
여기에 가시면 주요특징을 나열해놨습니다.

PHP
어떤 분은 PHP가 너무 막강해져서 코딩하기 편해졌다고 하더라구요. 전 PHP를 안해봐서 패스 ㅠ

JavaScript and Ajax
또 어떤 분이 JavaScript코딩과 디버깅이 강력해졌다고 하더군요. 이건 정말 좋군요. 예전에 선테크데이에서 CSS와 JavaScript코드하이라이팅 등의 기능을 보여줬는데, 너무 잘 되더라구요^^ 그 외에 유명한 JS Framework를 지원하네요^^

Java EE & Web Development
향상된 Spring, Hibernate, JSF, JPA 등을 지원한다는군요. 이번버전에서 Hibernate에 신경을 많이 썼더고 쓰리다가 그랬던 것 같은데요. Hibernate가 대세이긴 한가봅니다^^ 저도 공부해봐야겠습니다 ㅠ

JavaFX
이건 아직 Preview SDK인데요. 선테크데이에서 드래그앤드랍코딩으로 손쉽게 애플리케이션을 만들었습니다. 앞으로 JavaFX 기대해도 좋을 듯 싶습니다. 공식지원하나봅니다. 아직 SDK가 Beta도 아닌데.....-_-;

GlassFish v3 Prelude for Web Development
이거 선테크데이에서 OSGi랑 설명을 하던데...잘 모르므로 패스-_-;

C/C++
저기 특징중에 좀 맘에 드는 것이 Remote development라는 것이 있는데요. 저것이 된다면 엄청 편하겠는데요? 한번 해봐야겠습니다. C쪽은 보통 서버에서 컴파일되서 돌아가는 프로그램이 많아서-_-; 원격 개발이 되야합니다 ㅠ

그 외 Debugger도 향상되고, 이것저것 많이 향상되었네요.
전 맘에 드는 기능은 JavaFX랑 Hibernate랑 Javascript! 자....공부하러 고고싱~

 
Posted by 머드초보
,
 
셋팅이 완료되었으니 이제 controller를 만들어봅시다.
src폴더에 openidtest.controller라는 package를 만듭시다.
그리고, OpenIDController클래스를 생성합니다.
OpendIDController.java
[code]
package openidtest.controller;

import java.io.IOException;
import java.util.List;

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

import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
import org.openid4java.server.RealmVerifier;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class OpenIDController
{
private ConsumerManager manager;
   
    @RequestMapping(value="/index.do", method=RequestMethod.GET)
    public String indexGetcontroller(ModelMap model)
    {
        return "index";
    }
   
    @SuppressWarnings("unchecked")
    @RequestMapping(value="/index.do", method=RequestMethod.POST)
    public String indexPostController(String openId, ModelMap model,
            HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            manager = new ConsumerManager();
           
            String returnToUrl = "http://localhost:8080/OpenIdTest/verify.do";
           
            List discoveries = manager.discover(openId);
            if (discoveries.size() == 0)
            {
                model.addAttribute("noopenid", openId);
                return "index";
            }
            DiscoveryInformation discovered = manager.associate(discoveries);
            request.getSession().setAttribute("openid-disc", discovered);
            RealmVerifier rv = new RealmVerifier();
            rv.setEnforceRpId(false);
            manager.setRealmVerifier(rv);
            AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
           
            if (!discovered.isVersion2())
            {
                // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
                // The only method supported in OpenID 1.x
                // redirect-URL usually limited ~2048 bytes
                response.sendRedirect(authReq.getDestinationUrl(true));
                return null;
            } else {
                // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

                // RequestDispatcher dispatcher =
                // getServletContext().getRequestDispatcher("formredirection.jsp");
                // httpReq.setAttribute("prameterMap",
                // response.getParameterMap());
                // httpReq.setAttribute("destinationUrl",
                // response.getDestinationUrl(false));
                // dispatcher.forward(request, response);
            }
           
        }
        catch (OpenIDException e)
        {
        }
        return null;
        //model.addAttribute("openId", openId);
        //return "index";
    }
   
    @RequestMapping(value="/verify.do", method=RequestMethod.GET)
    public String verifyController(String openId, ModelMap model,
            HttpServletRequest request,
            HttpServletResponse response) throws ServletException
    {
        try
        {
            ParameterList paramList = new ParameterList(request.getParameterMap());
            DiscoveryInformation discovered = (DiscoveryInformation) request
            .getSession().getAttribute("openid-disc");
           
            // extract the receiving URL from the HTTP request
            StringBuffer receivingURL = request.getRequestURL();
            String queryString = request.getQueryString();
            if (queryString != null && queryString.length() > 0)
                receivingURL.append("?").append(request.getQueryString());
           
            // verify the response; ConsumerManager needs to be the same
            // (static) instance used to place the authentication request
            VerificationResult verification = manager.verify(receivingURL.toString(),
                    paramList, discovered);
           
            // examine the verification result and extract the verified
            // identifier
            Identifier verified = verification.getVerifiedId();
            if (verified != null)
            {
                request.getSession()
                    .setAttribute("openid", verified.getIdentifier());
            }
        }
        catch (OpenIDException e)
        {
        }
       
        return "redirect:index.do";
    }
   
    @RequestMapping(value="/logout.do", method=RequestMethod.POST)
    public String logoutController(String openId, ModelMap model,
            HttpServletRequest request,
            HttpServletResponse response) throws ServletException
    {
        request.getSession().removeAttribute("openid");
        return "redirect:index.do";
    }
}
[/code]
WEB-IINF/jsp/index.jsp
[code]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>오픈아이디 테스트</title>
</head>
<body>
<c:choose>
    <c:when test="${sessionScope.openid != null}">
        ${sessionScope.openid}님 환영합니다.
        <form action="logout.do" method="POST">
            <input type="submit" value="로그아웃"/>
        </form>
    </c:when>
    <c:otherwise>
        <form action="index.do" method="POST">
            <input type="text" id="openId" name="openId"/>
            <input type="submit" value="로그인"/>
        </form>
    </c:otherwise>
</c:choose>
<c:if test="${noopenid != null}">
    ${noopenid}는 없는 아이디입니다.
</c:if>
</body>
</html>
[/code]
view페이지에서 아이디를 치고, post요청을 하게 되면 indexPostController메소드가 호출이 됩니다. 여기서는 인증할 수 있는 URL을 redirect하게 됩니다. 그러면 OpenID를 제공하는 Provider에서 인증을 받고, returnURL로 이동을 해서 인증이 되었는지 확인 후 인증이 되면
Identifier verified = verification.getVerifiedId();
에서 Identifier 객체를 받을 수 있는데요. 이곳에서 오픈아이디를 구할 수 있습니다.

아 졸려-_-

 
Posted by 머드초보
,
 
우선 rath님이 올리신 글과 outsider님이 올리신 글을 참조했습니다.
(거의 똑같네-_-)

근데 이상하게 톰캣로그에서는 에러가 막 떨어지는데, 되네요-_-; 좀 더 확인해봐야겠네요 ㅠ

xrath님의 J2EE 환경에서 OpenID 지원 사이트 구축해보기
outsider님의 http://blog.outsider.ne.kr/164 http://blog.outsider.ne.kr/166

테스트환경은 TOMCAT6.0.18 + JDK 6u10 + Spring 2.5.6 입니다.

우선 http://code.sxip.com/ 이곳에서 라이브러리를 받습니다.
이클립스를 열어서 프로젝트를 하나 만듭시다.

Dynamic Web Project로 해서 만듭시다.
OpenIdTest라는 프로젝트로 만듭시다.

WEB-INF/lib에 라이브러리를 복사해야합니다. java-openid-sxip-0.9.4.jar이거 하나만 있으면 되는 줄 알았는데, lib폴더에 있는거 거의 다 필요하더군요-_-;
java-openid-sxip-0.9.4.jar
lib/commons-codec-1.3.jar
lib/commons-httpclient-3.0.1.jar
lib/commons-logging-1.03.jar
lib/htmlparser.jar
lib/openxri-client.jar
lib/openxri-syntax.jar
lib/endorsed/dom3-xercesImpl.jar
lib/endorsed/dom3-xml-apis.jar
lib/endorsed/xalan-2.6.0.jar
lib/xri/xmlsec-1.1.jar

그 외, 스프링과 jstl을 사용하기 위한 라이브러리를 복사합니다.
spring.jar
spring-webmvc.jar
standard.jar
jstl.jar

스프링을 위한 셋팅을 해봅시다.
web.xml파일을 수정합니다.
[code]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>OpenIdTest</display-name>

    <!-- SPRING FRAMEWORK DISPATCHER SERVLET CONFIGURATIONS -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class> org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>
[/code]
WebContent밑에 redirect.jsp파일을 생성합니다.
redirect.jsp
[code]
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>OPENID TEST</title>
</head>
<body>
<% response.sendRedirect("index.do"); %>
</body>
</html>
[/code]
WEB-INF 밑에 spring-servlet.xml을 생성합니다.
spring-servlet.xml
[code]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- ANNOTATION CONTEXT DEFINITION -->
    <context:annotation-config />
    <context:component-scan base-package="openidtest" />
   
    <!-- VIEW RESOLVER CONFIGURATIONS -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
   
</beans>
[/code]
아... 이제 셋팅이 완료되었어요.
다음 글에 계속.....-_-;

 
Posted by 머드초보
,
 
필터링 해야할 일이 생겨서 해봤습니다.

File클래스에는 list()메소드가 2개가 있습니다.
하나는 해당 디렉토리에서 모든 파일 리스트를 리턴하는 메소드입니다.
다른 하나는 필터링을 할 수 있게 FilenameFilter를 파라메터로 받는 list메소드가 있습니다.

두번째 것을 이용해서 원하는 파일을 필터링 할 수 있습니다.

FilenameFilter는 Interface입니다. 그래서 accept메소드를 구현하면 됩니다. 이 메소드에서 true값을 가지게 하는 값만이 String[]으로 반환이 됩니다.

[code]
import java.io.File;
import java.io.FilenameFilter;

public class FileFilterTest {

    public static void main(String[] args)
    {
        File file = new File("D:/");
        String[] list = file.list(new FilenameFilter()
        {
            @Override
            public boolean accept(File dir, String name)
            {
                return name.endsWith(".mp3");
            }
        });
       
        for (int i = 0; i < list.length; i++)
        {
            System.out.println(list[i]);
        }
    }
}
[/code]
[code]
01. War.mp3
01_Be.mp3
01 ) 나를 보낸다.mp3
더 크로스 3집 ['07 The Cross]- 01 Love Song.mp3
[/code]
음.....잘되는군요. 저 accept함수를 잘만 구현하면 원하는 형태로 구현할 수 있는 것 같습니다.

 
Posted by 머드초보
,