레이블이 Java인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Java인 게시물을 표시합니다. 모든 게시물 표시

2016년 9월 18일 일요일

이클립스에서 Swing 실행하기

import javax.swing.JFrame;

public class SwingApplication extends JFrame {
private JFrame frame;

public SwingApplication() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
try {
SwingApplication window = new SwingApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}

2015년 7월 21일 화요일

JPA2.0 & JPA2.1

JPA 2.0
  • Expanded object-relational mapping functionality
    • support for collections of embedded objects, linked in the ORM with a many-to-one relationship
    • ordered lists
    • combinations of access types
  • A criteria query API
  • standardization of query 'hints'
  • standardization of additional metadata to support DDL generation
  • support for validation
  • Shared object cache support.

JPA 2.1
  • Converters - allowing custom code conversions between database and object types.
  • Criteria Update/Delete - allows bulk updates and deletes through the Criteria API.
  • Stored Procedures - allows queries to be defined for database stored procedures.
  • Schema Generation
  • Entity Graphs - allow partial or specified fetching or merging of objects.
  • JPQL/Criteria enhancements - arithmetic sub-queries, generic database functions, join ON clause, TREAT option.


STEP2. 버전에 따른 변경 감지하기

2015년 7월 20일 월요일

JDBC(Java Database Connectivity)

자바 프로그램 내에서 데이터베이스 질의문 즉, SQL을 실행하기 위한 자바 API(application programming interface)이다. Java database connectivity의 약자로 생각하기도 하지만 실제로는 상표 이름이다. JDBC는 데이터베이스 및 애플리케이션 개발자들을 위한 표준 API를 제공하고 순수 자바 API만으로도 데이터베이스 응용업무를 만들게 해준다.
JDBC를 사용하면, 어떠한 관계 데이터베이스(relational database)에서도 SQL문을 사용하기 쉽다. 즉, JDBC API를 사용하면 DB2, Sybase, Oracle, Informix, mSQL 등의 데이터베이스에 접근하는 프로그램을 따로 만들 필요가 없다. 단지 하나의 프로그램을 작성하고 그 프로그램에서 SQL문을 적당한 데이터베이스에 전송할 수 있다.

출처 : http://terms.naver.com/entry.nhn?docId=1180032&cid=40942&categoryId=32837



JDBC is a Java database connectivity technology (Java Standard Edition platform) from Oracle Corporation. This technology is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment.

출처 : https://en.wikipedia.org/wiki/Java_Database_Connectivity



The JDBC API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC API provides a call-level API for SQL-based database access. JDBC technology allows you to use the Java programming language to exploit "Write Once, Run Anywhere" capabilities for applications that require access to enterprise data.

출처 : http://www.oracle.com/technetwork/java/overview-141217.html




STEP1. 바닥부터.. 다시한번 훑어보자.    Write Once, Run Anywhere

2012년 8월 11일 토요일

SpringMVC Tip

서블릿 매칭을 제외한 스프링프레임웍으로부터 현재 매핑된 주소 동적으로 가져오기


Case1. 단순매칭시

@RequestMapping(value=[이부분], method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse){
    String mappingValue = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    System.out.println("Mapping Value = "  + mappingValue);
    return new ModelAndView("index");
}


Case2. url 변수 사용시

@RequestMapping(value=index. + "{val}", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse,
    @PathVariable("val") final String val){
    String mappingValue = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    Map<?, ?> mapping = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    Iterator<?> iter = mapping.keySet().iterator();
    while(iter.hasNext()){
        String key = (String) iter.next();
        Object value = mapping.get(key);
        if(mappingValue.contains("{"+key+"}")){
            mappingValue = mappingValue.replaceAll("\\{"+key+"\\}", value == null ? "" : value.toString());
        }
    }
    System.out.println("Mapping Value = "  + mappingValue);
    return new ModelAndView("index");
}


참고

2012년 7월 9일 월요일

[JAVA] My .properties file loader




import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Properties;
import java.util.TimeZone;
/**
 *
 * @author pig
 *
 */
public class Loader {

public static String getPropertieValue(String key) {
String value=Loader.getInstance().getPropertie(key);
if(value == null){
System.out.println("not find ["+key+"] from init.properties file");
System.out.println("set "+key+" : null");
}else{
System.out.println("set "+key+" : " + value);
}
return value;
}
public static TimeZone getDefaultTimeZone() {
String timeZoneStr = Loader.getInstance().getPropertie("default.time.zone");
TimeZone timezone;
if(timeZoneStr == null){
timezone = Calendar.getInstance().getTimeZone();
System.out.println("not find [default.time.zone] from init.properties file");
System.out.println("set default timezone(take value from system) : " + timezone.getDisplayName());
}else{
timezone = TimeZone.getTimeZone(timeZoneStr);
System.out.println("set default timezone : " + timezone.getDisplayName());
}
return timezone;
}
private static final Loader loader = new Loader();

public static Loader getInstance() {
return loader;
}

private Properties properties = new Properties();
private Loader() {

try {
//System.out.println(this.getClass().getResource("/"));
URL url = new URL("file:" + this.getClass().getResource("").getFile().split("classes")[0] + "classes/init.properties");
System.out.println("--Load : init.properties-------------------------------------------------------------------");
System.out.println("--necessery properties file : init.properties");
System.out.println("--properties file location : " + url.getPath());
System.out.println("--develop by oneofworld.com");
//System.out.println("--v0.1");
properties.load(url.openStream());
System.out.println("--Load properties SUCCESS");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("--Load properties FAIL : " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("--Load properties FAIL : " + e.getMessage());
}
System.out.println("-------------------------------------------------------------------------------------------");
}
public Properties getProperties() {
return properties;
}
public String getPropertie(String key) {
return properties.getProperty(key);
}
}


2012년 6월 6일 수요일

[JSP] 브라우저 파일 다운로드창에서 한글깨짐

파일명을 UTF-8로 인코딩 해준다.

response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8") + ";");


2012년 4월 24일 화요일

[Hibernate] Hibernate4 TransactionFactory Class

혹시나 필요한 분들을 위해

Hibernate3 -> Hibernate4
--------------------------------------------------------------------
org.hibernate.transaction.JDBCTransactionFactory
->
org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
--------------------------------------------------------------------
org.hibernate.transaction.JTATransactionFactory
->
org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory
--------------------------------------------------------------------
org.hibernate.transaction.CMTTransactionFactory
->
org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory



출처 : http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e596

2012년 4월 9일 월요일

[JSP] 페이지 응답상태 지정

response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT); //504
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); //401
response.setStatus(HttpServletResponse.SC_FORBIDDEN); //403

----------------------------------------------------------------------
페이지 상태코드 정의목록

javax.servlet.http
Interface HttpServletResponse

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html

2012년 3월 4일 일요일

[Hibernate] Hibernate 4 에서의 getSessionFactory

Hibernate 4.0 메뉴얼상의 HibernateUtil 
-------------------------------------------------------------------------
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html_single/
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
-------------------------------------------------------------------------
하지만 buildSessionFactory() 가 deprecation 된 상태이다
Deprecated. Use buildSessionFactory(ServiceRegistry) instead
라고나와있다
그래서 새로운 소스로 대체하였다.
-------------------------------------------------------------------------
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
 * http://stackoverflow.com/questions/8621906/is-buildsessionfactory-deprecated-in-hibernate-4
 */
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (HibernateException ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

2011년 8월 16일 화요일

[SpringFramework] 스프링MVC(SpringMVC) 애노테이션(Annotation)을 이용한 URI컨트롤


Spring 알수록 매력적


@RequestMapping(value="/basic.{basicId}", method=RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse,
    @PathVariable("basicId") String basicId
    ) {
    System.out.println("id:" + basicId);
    return new ModelAndView("basic");
    }


@RequestMapping(value="/basic/{basicId}", method=RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse,
     @PathVariable("basicId") String basicId
     ) {
     System.out.println("id:" + basicId);
     return new ModelAndView("basic");
    }


@RequestMapping(value="/basic/*/{basicId}", method=RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse,
     @PathVariable("basicId") String basicId
     ) {
     System.out.println("id:" + basicId);
     return new ModelAndView("basic");
    }


2011년 6월 30일 목요일

[Java] Date to String

public static String convertDateToString(Date date) {
if(date == null) return null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 M월 d일, h시 m분 s초");
return formatter.format(date);
}

public static String convertDateToYear(Date date) {
if(date == null) return null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
return formatter.format(date);
}

public static String convertDateToMonth(Date date) {
if(date == null) return null;
SimpleDateFormat formatter = new SimpleDateFormat("MM");
return formatter.format(date);
}


public static String convertDateToDay(Date date) {
if(date == null) return null;
SimpleDateFormat formatter = new SimpleDateFormat("dd");
return formatter.format(date);
}

2011년 4월 5일 화요일

[Java] FileReader 한글깨짐

FileReader로 텍스트파일을 읽어오는데 한글이 계속 깨진다.


오랜시간 삽질끝에 원인을 알았다. 
인코딩때문이라면 설정할 곳이 없어 알아서 가져오나보다 했는데 그게 문제였다.
FileReader은 시스템의 인코딩으로 읽어온다고 한다.
읽으려는 파일은 UTF-8
InputStreamReader 을 사용하여 인코딩 설정을 하면 결과가 잘나온다.


String path = "???";
BufferedReader in = new BufferedReader(new FileReader(path));
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF8"));


.. 인코딩문제는 정말 머리 아프다.
인코딩에대한 이해가 없어 그런거겠지만;;


참조

2011년 1월 14일 금요일

[Java] 색상 정보 형태 변환

필요한데로 가공해서 쓰면 편리함

/** * 색상 정보 형태 변환 * @param strColorValue(RGB 16진수) ex)ff,ff,ff -> 255,255,255 * @return */ public static String getColorValueType2(String strColorValue) { String[] strColorValues = strColorValue.split(","); String strCovColor = String.format("%02x", Integer.parseInt(strColorValues[0], 10)) + String.format("%02x", Integer.parseInt(strColorValues[1], 10)) + String.format("%02x", Integer.parseInt(strColorValues[2], 10)); return strCovColor; } /** * 색상 정보 형태 변환 * @param strColorValue(RGB 16진수) ex)ffffff -> java.awt.Color * @return */ public static Color getColorType1(String strColorValue) { int r = Integer.parseInt(strColorValue.substring(0,2),16); int g = Integer.parseInt(strColorValue.substring(2,4),16); int b = Integer.parseInt(strColorValue.substring(4,6),16); return new Color(r,g,b); }

2011년 1월 12일 수요일

[Java] 세자리마다 <,> 표시하기

/**
* 세자리마다 <,> 표시
* @param d
* @return
*/
public static String getNumFromatInstance(double d) {
 NumberFormat nf = NumberFormat.getInstance();
 return nf.format(d);
}

2010년 11월 30일 화요일

[JSP] 접근주소 (Request Dispatcher Path) 가져오기

필터기능과 사용하면 페이지 접근 컨트롤 시에 유용함

String requestDispatcherPath = (String) request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);

2010년 11월 29일 월요일

[Java] enum을 이용하여 Swith문에 String형 사용하기

굳이 if 문 두고 이렇게 해야하는건 아니지만 개인적으로 if 문 보다는 switch 가 가독성이 좋다

public class Switch {
       public static void main(String[] args) {
              String str = "APPLE";
              switch (Enum.compare(str)) {
                     case APPLE:
                            System.out.println("apple");
                            break;
                     case BANANA:
                            System.out.println("banana");
                            break;
                     case BREAD:
                            System.out.println("bread");
                            break;
                     default:
                            System.out.println("novalue");
              }
       }

       public enum Enum {
              APPLE, BANANA, BREAD, NOVALUE;
              public static Enum compare(String str) {
                     try {
                            return valueOf(str.toUpperCase());
                     } catch (Exception ex) {
                            return NOVALUE;
                     }
              }
       }
}


참조