PC

블로그 이미지

DAVID

160527: 52회차

Programming 2016. 5. 27. 12:18

종료하기 전 티스토리 네이버 로그아웃 할 것


1. 툴

동일

추가시: 


2. 폴더

동일

추가시:


3. 사용할 사이트

동일

추가시:


4. 공부하는 것


[27][spring] Annotation 설정, component-scan

[01] Annotation 설정  

- Annotation 설정은  코드에 설정정보를 입력함으로써 설정파일을 사용하지 않거나  
  설정파일 크기를 줄이는데 유용합니다. 


  • @Autowired               -  의존하는 객체 주입 (필드,메소드/setter,생성자 에서 사용)        
                                         DI객체가 중복될때 Qualifier("") 사용
  • @Resource                 -  의존하는 객체 주입(필드,setter 에서 사용)
                                         DI객체가 중복될때 Resource(name="") 사용
  • @PostConstruct          -  객체 생성후 호출
  • @PreDestroy              -  객체가 소멸되기 바로전 호출
  • @Qualifier                 -  자동설정 제한하며, 수식어를 값으로 가짐
  • @Required                -  필수 프로퍼티를 명시 (setter 메소드에서 사용)                    
 

1.
 Annotation 예제 확인

      -  스프링 프로젝트의 설정 

        Project Type: Spring  Project --> Simple Spring Utility Project    
                Name: AnnoTest
             Package: spring.sts.annotation 
             Library: 프로젝트 생성시 관련 Spring 라이브러리가 자동으로 다운로드  
                      됩니다. 작업 컴퓨터는 인터넷에 연결되어 있어야 합니다. 



  packate: spring.sts.annotation


import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
 * 
 * @author Apurav
 *
 */
public class Foo {
    private String name;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    @PostConstruct
    public void init() {
        System.out.println("bean successfully initialized");
    }
    @PreDestroy
    public void cleanUp() {
        System.out.println("clean up called");
    }
 }
 

 
    


import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
 * 
 * @author AHN
 *
 */
public class Bar {
    @Autowired
    @Qualifier(value="secondaryFoo")
    private Foo foo;
    
    @Resource(name="foo")
    private Foo foo2;
    
    //@Required
    public void setFoo(Foo foo) {
        this.foo = foo;
    }
    public void  printFooName(){
        System.out.println(foo.getName());
        System.out.println(foo2.getName());
    }
    
}




import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * 
 * @author Apurav
 *
 */
public class TestFooBar {
 
    public static void main(String[] args) throws InterruptedException {
 
 
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "annotation.xml");
        Bar bar = applicationContext.getBean("bar", Bar.class);
        bar.printFooName();
        applicationContext.registerShutdownHook();
         
    }
 
}




>>>>>> annotation.xml


<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-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <context:annotation-config />
 
    <bean id="foo" class="spring.sts.annotation.Foo">
        <property name="name" value="Apurav"></property>
    </bean>
    <bean id="anotherFoo" class="spring.sts.annotation.Foo">
        <property name="name" value="AHN"></property>
        <qualifier value="secondaryFoo"></qualifier>
    </bean>
    <bean id="bar" class="spring.sts.annotation.Bar" />
</beans>



 
  • @Component           - @Repository, @Service 를 포괄적으로 사용 
  • @Controller             - @Component가 대신 사용될수 없음
 

         




  • @Service             -  business logic 의 서비스 패턴 클래스 에서 사용
  • @Repository        -  database access logic의  DAO 패턴 클래스 에서 사용



[02] xml설정파일에 등록없이 빈으로 사용가능한 스캔 

1. <context:component-scan> 

- @Component, @Service, @Controller가 적용된 클래스를 자동으로 등록해줍니다. 

<?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-3.0.xsd 
http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 


<context:component-scan base-package="spring.sts.annotation.*" /> 

</beans> 

 

2. <context:include-filter> 
   <context:exclude-filter> 

- 자동스캔대상에 포함시킬 클래스와 포함시키지 않을 클래스를 구체적으로  
  명시할 수 있습니다. 

<context:component-scan base-package="sts.hello.semple"> 
<context:include-filter type="regex" expression=" 
.*Mgr"/> 
<context:exclude-filter type="aspectj" expression=" 
..*Mgr"/> 
</context:component-scan> 

- regex:정규표현식 
- aspectj:Aspectj표현식 


[28][spring] @MVC, @MVC 기반 Spring MVC 프로젝트 실습, Local 저장소 변경

[01] Spring MVC Annotation  

    @Controller                    -  클래스 타입에만 적용되며,웹 요청처리에 사용
      @RequestMapping         -  컨트롤러가 처리할 요청 URL을 명시하는데 사용(클래스,메소드)


  1) 컨트롤러 메소드의 매개변수(파라메터) 타입

   


  2) 컨트롤러 메소드의 리턴값 타입
  
    



    @PathVariable               -  Parameter를 URL형식으로 받기
                                            
   ex)  1)일반 get방식으로 서버에서 값 확인

          http://127.0.0.1:8000/test?menu=board

        


          
           
          

          2) @PathVariable 를 이용하여 서버에서 값 확인


           http://127.0.0.1:8000/test/board

      
         


 
            





      @RequestParam   - Form페이지에서 넘어오는 파라메터를 받을수 있다.         
                                      - 
key=value 형태로 넘어오는 파라미터를 맵핑 된 메소드의 매개변수
                                값으로 설정 


           1) 해당 파라미터가 없다면 HTTP 400 - Bad Request 가 전달 된다. 

           2) file의 경우는 <input type="file" name="file" /> 에 매핑 된다. 

              public String edit( @RequestParam("id") int id,  
                      @RequestParam("title") String title,  
                      @RequestParam("file") MultipartFile file ) {...} 
  

          3) 맵 형태로 받으면 모든 파라미터 이름은 맵의 키에 파라미터 값은 맵의 값에
             담긴다.  


             public String add( @RequestParam Map<String, String> params ) {...} 


          4) 파라미터가 필수가 아니라면 required = false 로 지정하면 된다.  
             이때 파라미터가 없으면 NULL이 들어간다. default 값을 지정 할 수도 있다.  

             public void view( @RequestParam(value = "id",  
                                          required = false,  
                                      defaultValue = "0" )  int id) {..}. 


 
       @ModelAttribute              -  
파라미터를 Object(DTO) 형태로 받을때 사용

               ex) 
public void update( @ModelAttribute("board") Board board) {...} 

      @SessionAttributes          - 세션상에서 model의 정보를 유지하고 싶을 경우 사용
    @RequestBody           - HTTP body 부분만 전달 한다. XML 이나 JSON 으로 출력 할 
                                  경우 사용 

      @Value
             1)
 프로퍼티값이나 properties파일의 값을 필드나 파라미터에 적용한다. 


 public class BoardController { 
    @Value("${eng.url}")  
    String engUrl; 
  
    @RequestMapping(..) 
    public String gotoEng() { 
        return this.engUrl; 
    } 
} 
  


          2) 위는 프로퍼티중 eng.url 의 값을 String engUrl에 매핑 시켰으며 메소드의 
             파라미터에도 적용 된다. 


 public String gotoEng( @Value("${eng.url}") String engUrl ) { 
     return engUrl; 
}       



               3) Project Type: Spring  Project --> Simple Spring Utility Project    
            Name: ValueTest 
            Package: spring.annotation.value 
            Library: 프로젝트 생성시 관련 Spring 라이브러리가 자동으로 다운로드  
                  됩니다. 작업 컴퓨터는 인터넷에 연결되어 있어야 합니다. 
  


>>>>   ExampleService .java

package spring.annotation.value;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
 
/**
 * {@link Service} with hard-coded input data.
 */
@Component
public class ExampleService implements Service {
 
@Value("#{sv['server.name']}")
private String name;
 
@Value("#{sv['server.id']}")
private String id;
 
/**
* Reads next record from input
*/
public String getMessage() {
return "name: "+name+"\n"+"id: "+id; 
}
 
}




>>>> META-INF/spring/app-context.xml
 
<?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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
">
 
<description>Example configuration to get you started.</description>
 
<context:component-scan base-package="spring.annotation.value" />
 
    <util:properties id="sv" location="classpath:config.properties" />
</beans>
 
 
>>>>>> Test.java
 
 
package spring.annotation.value;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Test {
 
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("META-INF/spring/app-context.xml");
 
Service se =(Service)context.getBean("exampleService");
 
System.out.println(se.getMessage());
}
 
}

             

 
>>>>>>> config.properties
 
server.name=tomcat
server.id=java

  


 [02] 
@MVC 기반 Spring MVC 프로젝트

  1.Project Type: Spring  Project --> Spring MVC Project    
            Name: mvc_book 
         Package: spring.mvc.book 
           Library: 프로젝트 생성시 관련 Spring 라이브러리가 자동으로 다운로드  
                     됩니다. 작업 컴퓨터는 인터넷에 연결되어 있어야 합니다. 



    -  프로젝트 구성   
    /mvc_book/src/main/java                    : Java class 저장 폴더 
    /mvc_book/src/main/webapp/resources        : CSS, JS, Image등의 리소스 
    /mvc_book/src/main/webapp/WEB-INF          : Web 환경 설정  
    /mvc_book/src/main/webapp/WEB-INF/spring   : Spring 환경 설정  
    /mvc_book/src/main/webapp/WEB-INF/views    : Spring jsp file 




>>>> web.xml (한글처리용 필터추가)

    :
    :

 <filter> 
  <filter-name>encodingFilter</filter-name> 
  <filter-class> 
    org.springframework.web.filter.CharacterEncodingFilter 
  </filter-class> 
  <init-param> 
   <param-name>encoding</param-name> 
   <param-value>UTF-8</param-value> 
  </init-param> 
 </filter> 

 <filter-mapping> 
    <filter-name>encodingFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
 </filter-mapping> 

     :
     :
 



>>>> BookCon.java 

package spring.mvc.book; 

import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.servlet.ModelAndView; 

import java.text.DecimalFormat;

@Controller 
@RequestMapping("/book.s3") 
public class BookCon { 
  public BookCon(){ 
    System.out.println("BookCon 객체 생성" ); 
  } 
   
  @RequestMapping(method=RequestMethod.GET) 
  protected ModelAndView execute(Model model) { 
       
      ModelAndView mav = new ModelAndView(); 
      mav.setViewName("/book/form");  // form.jsp 
       
      return mav; 
  } 
   
  @RequestMapping(method=RequestMethod.POST) 
  protected ModelAndView execute(String bookname, String name, String publisher, int pay) { 
       
     DecimalFormat df = new DecimalFormat("###,###,###"); 
 
 
      ModelAndView mav = new ModelAndView(); 
      mav.setViewName("/book/proc");  // proc.jsp 
      mav.addObject("bookname", bookname); 
      mav.addObject("publisher", publisher); 
      mav.addObject("name", name); 
      mav.addObject("pay", df.format(pay)); 
       
      return mav;
  } 
} 



>>>>src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml 

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:beans="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
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"> 

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

<!-- Enables the Spring MVC @Controller programming model --> 
<annotation-driven /> 

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
<resources mapping="/**" location="/" /> 

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
<beans:property name="prefix" value="/WEB-INF/views/" /> 
<beans:property name="suffix" value=".jsp" /> 
</beans:bean> 

<context:component-scan base-package="spring.mvc.book" /> 



</beans:beans> 





>>>>>>src/main/webapp/book/images/logo_kyobo.gif 
 
 - 홈페이지에서 다운로드




>>>>>src/main/webapp/WEB-INF/views/book/form.jsp 


<%@ page contentType="text/html; charset=utf-8" %> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
 <HEAD> 
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
  <TITLE> 도서 주문 신청 </TITLE> 
 </HEAD> 

 <BODY> 
 <img src="${pageContext.request.contextPath}/book/images/logo_kyobo.gif" width="20%"> 
 <br><br> 
 [[ 도서 주문 신청 ]]<br> 
 <form name="frmCreate"  
          action="./book.s3" 
          method="post"> 
   책 제목:<input type="text" name="bookname" value="개구리의 기도" style="width: 252px; "/><br> 
   저자 : <input type="text" name="name" value="앤서니 드 멜로"/><br> 
   출판사 : <input type="text" name="publisher" value="분도"/><br> 
   가격 : <input type="text" name="pay" value="12000"/><br> 

   <input type="submit" name="btnSubmit" value="주문" /> 
 </form> 

 </BODY> 
</HTML> 



>>>>>src/main/webapp/WEB-INF/views/book/proc.jsp 


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
 <HEAD> 
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
  <TITLE>[[ 도서 주문 신청  결과 ]] </TITLE> 
 </HEAD> 
 
 <BODY> 
 <H2> 
 
책 제목 : ${bookname} <br/> 
   저자 : ${name}     <br/> 
 출판사 : ${publisher} <br/> 
   정가 : ${pay} 
   
 <br/>
 </H2> 
</body>
</html>







2. 서비스 파일의 생성 확인 

D:/rfid02/spring/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mvc_book/resources 폴더에  

JSP 관련 파일이 통합되어 들어감 





[03] Local 저장소의 변경 


- 메이븐은 기본적으로 저장소를 운영체제의 계정을 따라 생성된다. 
  'C:/Users/STU/.m2' 하지만 이경로는 개발환경이 바뀌면 불편함으로 수동으로 
  저장소를 지정할 수 있다. 

- 기본 경로에있는 jar 파일이 인식이 안되는 경우 인식이됨. 

- 라이브러리를 운영체제로부터 분리하여 이동가능. 


1. Maven 설정 파일의 생성 
>>>>> F:/eGov/spring/maven/settings.xml 
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 
                              http://maven.apache.org/xsd/settings-1.0.0.xsd"> 
    <localRepository> F:/
eGov/spring/maven</localRepository> 
    <interactiveMode>true</interactiveMode> 
    <usePluginRegistry>false</usePluginRegistry> 
    <offline>false</offline> 
    <pluginGroups> 
        <pluginGroup>org.codehaus.mojo</pluginGroup> 
    </pluginGroups> 
</settings> 



2. Eclipse 설정 

Eclipse STS -> Window -> Preferences -> Maven -> User Settings 
- User Settings: settings.xml 



3. STS를 재시작하면 새로운 저장소로 jar를 다운 받는다. 


4. 실행 
   http://localhost:8000/book/home 


1) 최초 프로젝트 생성시 마지막 패키지 이름이 URL Path(Root Context Path)으로 지정 

   Package: sts.mvc.book 

   URL: http://localhost:8089/book/ 


[참고] 변경이 필요한경우 

   Servers --> Tomcat v7.0 Server at localhost-config --> server.xml 
  
<Context docBase="sts_mvc" path="/book" reloadable="true" source="org.eclipse.jst.jee.server:sts_mvc_book"/></Host> 

부분의 path 속성의 값을 path="/bookcbd" 부분을 변경 

   URL: http://localhost:8000/bookcbd/ 



[30][spring][board] model 작성 DTO, DAO, Mgr, View페이지 다운
>>> spring.model.board.BoardDTO.java 
 
package spring.model.board; 
 
import org.springframework.web.multipart.MultipartFile; 
 
public class BoardDTO { 
    private int  num ;  // 글 일련 번호 
    private String  name;      // 글쓴이 성명 
    private String  subject; // 제목 
    private String  content; // 내용 
    private int    ref; // 부모글 번호(그룹번호) 
    private int    indent; // 답변여부,깊이 
    private int    ansnum; // 답변 순서(최신답변은 부모글 바로 아래 달려집니다.) 
    private String  regdate; // 글 등록일 
    private String  passwd; // 패스워드 
    private int    count; // 조회수  
    private String  ip; // 글쓴이 IP  
    private MultipartFile filenameMF; //form에서 <input type=file name="filenameMF">★★★★(중요) 
    private String  filename; // 파일명  
    private int    filesize; // 파일 사이즈 
    private int    refnum; // 답변확인 컬럼 
    
    public int getNum() { 
        return num; 
    } 
    public void setNum(int num) { 
        this.num = num; 
    } 
    public String getName() { 
        return name; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
    public String getSubject() { 
        return subject; 
    } 
    public void setSubject(String subject) { 
        this.subject = subject; 
    } 
    public String getContent() { 
        return content; 
    } 
    public void setContent(String content) { 
        this.content = content; 
    } 
    public int getRef() { 
        return ref; 
    } 
    public void setRef(int ref) { 
        this.ref = ref; 
    } 
    public int getIndent() { 
        return indent; 
    } 
    public void setIndent(int indent) { 
        this.indent = indent; 
    } 
    public int getAnsnum() { 
        return ansnum; 
    } 
    public void setAnsnum(int ansnum) { 
        this.ansnum = ansnum; 
    } 
    public String getRegdate() { 
        return regdate; 
    } 
    public void setRegdate(String regdate) { 
        this.regdate = regdate; 
    } 
    public String getPasswd() { 
        return passwd; 
    } 
    public void setPasswd(String passwd) { 
        this.passwd = passwd; 
    } 
    public int getCount() { 
        return count; 
    } 
    public void setCount(int count) { 
        this.count = count; 
    } 
    public String getIp() { 
        return ip; 
    } 
    public void setIp(String ip) { 
        this.ip = ip; 
    } 
    public String getFilename() { 
        return filename; 
    } 
    public void setFilename(String filename) { 
        this.filename = filename; 
    } 
    public int getFilesize() { 
        return filesize; 
    } 
    public void setFilesize(int filesize) { 
        this.filesize = filesize; 
    } 
    public int getRefnum() { 
        return refnum; 
    } 
    public void setRefnum(int refnum) { 
        this.refnum = refnum; 
    } 
    public MultipartFile getFilenameMF() { 
        return filenameMF; 
    } 
    public void setFilenameMF(MultipartFile filenameMF) { 
        this.filenameMF = filenameMF; 
    } 
} 
 
 
 
>>> spring.model.board.BoardMgr.java 
 
package spring.model.board; 
 
import java.sql.Connection; 
import java.sql.SQLException; 
import java.util.List; 
import java.util.Map; 
import org.springframework.beans.factory.BeanFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource; 
import org.springframework.core.io.Resource; 
import org.springframework.stereotype.Service; 
 
import spring.utility.board.DBClose;
import spring.utility.board.DBOpen;
 
@Service 
public class BoardMgr { 
@Autowired 
private BoardDAO dao; 
 
public BoardMgr() { 
    super(); 
} 
 
/** 
 * 글쓰기 
 * @param dto 
 * @return 
 */ 
public boolean create(BoardDTO dto){ 
    boolean flag = false; 
    Connection con=null; 
    try{ 
        con=DBOpen.getConnection(); 
    flag = dao.create(dto, con); 
 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
 
    return flag; 
    } 
 
/** 
 * 전체 레코드 갯수 
 * @return 
 */ 
public int getTotal(Map map){ 
    int total=0; 
    Connection con = null;
    try{ 
     con = DBOpen.getConnection();
        total = dao.getTotal(map, con); 
 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
    return total; 
} 
/** 
 * 글 목록 
 * @param searchColumn 검색컬럼 
 * @param searchWord   검색어 
 * @param beginPerPage 시작레코드번호 
 * @param numPerPage   한페이지당보여줄 레코드 갯수(10) 
 * @return 페이지에 보여줄 글의목록들 
 */ 
public List getList(Map map){ 
     
    List v = null; 
    Connection con = null; 
    try{ 
        con = DBOpen.getConnection(); 
        v = dao.getList(map, con); 
 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
    return v; 
} 
 
 
/** 
 * 조회수 증가 
 * @param num 
 */ 
public void upCount(int num){ 
    Connection con = null; 
    try{ 
     con = DBOpen.getConnection();
        dao.upCount(num, con); 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
} 
/** 
 * 특정게시판 내용보기 
 * @param num 
 * @return 
 */ 
public BoardDTO read(int num){ 
    BoardDTO dto = null; 
    Connection con = null; 
    try{ 
        con = DBOpen.getConnection(); 
        dto = dao.read(num, con); 
 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
    return dto; 
} 
 
/** 
 * 비빌번호 확인 
 * @param num 
 * @param passwd 
 * @return 
 */ 
public boolean passwdCheck(int num, String passwd){ 
    boolean flag = false; 
    Connection con = null;
    try{ 
     con = DBOpen.getConnection(); 
        flag = dao.passwdCheck(num,passwd, con); 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
    return flag; 
} 
 
/** 
 * 게시판 글수정 
 * @param dto 
 * @return 
 */ 
public boolean update(BoardDTO dto){ 
    boolean flag = false; 
    Connection con = null; 
    try{ 
        con = DBOpen.getConnection(); 
        flag = dao.update(dto, con); 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
return flag; 
} 
/** 
 * 답변처리  
 * 1.부모의 또다른 답변의 순서(ansnum)를  
 *   1증가 시켜줌(UPDATE) 
 * 2.새로운 답변글을 인서트 함(INSERT) 
 * @param dto 
 * @return 
 */ 
public boolean reply(BoardDTO dto){ 
    boolean flag = false; 
    Connection con = null;
    try{ 
     con = DBOpen.getConnection(); 
        con.setAutoCommit(false); 
        //ansnum의 순서를 재정렬 
        dao.upAnsnum(dto.getRef(),dto.getAnsnum(), con); 
        //답변글을 등록(ref는부모글의 ref와 같아야하고,indent, ansnum 
        //부모글보다 1증가한 값으로 등록) 
        flag = dao.insertReply(dto, con); 
        //실제로 DB에 적용하라... 
        con.commit(); 
        }catch(Exception e){ 
        System.out.print(e); 
    try{ 
        //지금까지의 문장을 취소처리하라.. 
        con.rollback(); 
    }catch(Exception ex){} 
    }finally{ 
    try{ 
       con.setAutoCommit(true); 
    }catch(Exception ex){} 
        DBClose.close(con); 
    } 
    return flag; 
    } 
 
    /** 
     * 부모글인지 확인 
     * @param num 
     * @return 
     */ 
public boolean checkRefnum(int num){ 
    boolean flag = false; 
    Connection con = null;
    try{ 
     con = DBOpen.getConnection(); 
        flag = dao.checkRefnum(num,con); 
    }catch(Exception e){ 
        System.out.print(e); 
    }finally{ 
        DBClose.close(con); 
    } 
    return flag; 
} 
 
/** 
 * 게시판 글 삭제 
 * @param num 
 * @return 
 */ 
public boolean delete(int num){ 
    boolean flag = false; 
    Connection con = null; 
    try{ 
     con = DBOpen.getConnection();
        flag = dao.delete(num, con); 
 
    }catch(Exception e){ 
        System.out.print(e); 
         
    }finally{ 
        
        DBClose.close(con); 
    } 
    return flag; 
} 
 
 
} 
 
 
>>> spring.model.board.BoardDAO.java 
 
package spring.model.board; 
 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
 
import org.springframework.stereotype.Component; 
 
import spring.utility.board.DBClose;
 
@Component 
public class BoardDAO { 
 
/** 
 * 글쓰기 처리 
 * @param dto 
 * @return 
 */ 
public boolean create(BoardDTO dto,Connection con)throws Exception { 
    boolean flag = false; 
    PreparedStatement pstmt = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" INSERT INTO board(num, name, passwd, subject, content,"); 
    sql.append(" regdate, ref, ip, filename, filesize )"); 
    sql.append(" VALUES(board_seq.Nextval,?,?,?,?,sysdate,?,?,?,?) "); 
    //부모글번호 생성 
    int ref=getRef(con); 
    dto.setRef(ref); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setString(1, dto.getName()); 
        pstmt.setString(2, dto.getPasswd()); 
        pstmt.setString(3, dto.getSubject()); 
        pstmt.setString(4, dto.getContent()); 
        pstmt.setInt(5, dto.getRef()); 
        pstmt.setString(6, dto.getIp()); 
        pstmt.setString(7, dto.getFilename()); 
        pstmt.setInt(8, dto.getFilesize()); 
        int cnt = pstmt.executeUpdate(); 
        if(cnt>0) flag = true; 
 
 
    }finally{ 
        DBClose.close(pstmt); 
    } 
 
    return flag; 
} 
/** 
 * 부모글번호 생성 
 * @return int 부모글번호 
 */ 
private int getRef(Connection con)throws Exception { 
    int ref = 0; 
    PreparedStatement stmt = null; 
    ResultSet rs = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" SELECT NVL(MAX(ref),0) + 1 FROM board "); 
 
    try{ 
        stmt = con.prepareStatement(sql.toString()); 
        rs = stmt.executeQuery(); 
        if(rs.next()){ 
            ref = rs.getInt(1); 
         } 
 
    }finally{ 
        DBClose.close(stmt, rs); 
    } 
 
    return ref; 
} 
/** 
 * 전체 레코드 갯수 
 * @param searchColumn 
 * @param searchWord 
 * @return 
 */ 
public int getTotal(Map map, Connection con) 
throws Exception  
{ 
    int total =0; 
    PreparedStatement pstmt=null; 
    ResultSet rs = null; 
 
    String col = (String)map.get("col"); 
    String word = (String)map.get("word"); 
 
    StringBuffer sql = new StringBuffer(); 
 
    sql.append(" SELECT COUNT(*) FROM board "); 
 
    if(word.length >0 && col.equals("subject_content")){ 
        sql.append(" WHERE (subject LIKE "+"'%"+word+"%' "); 
       sql.append(" OR content LIKE "+"'%"+word+"%') "); 
    }else if(word.length >0)){ 
       sql.append(" WHERE "+col+" LIKE "+"'%"+word+"%' "); 
    } 
    try{ 
       pstmt = con.prepareStatement(sql.toString()); 
       rs = pstmt.executeQuery(); 
       if(rs.next()){ 
          total = rs.getInt(1); 
       } 
 
    }finally{ 
        DBClose.close(pstmt, rs); 
    } 
 
    return total; 
 
} 
/** 
 * 게시판 글목록 
 * @param searchColumn 
 * @param searchWord 
 * @param beginPerPage 
 * @param numPerPage 
 * @return 
 */ 
public List getList(Map map, Connection con) 
throws Exception 
{ 
    List list = new ArrayList(); 
    PreparedStatement pstmt = null; 
    ResultSet rs = null; 
 
    String col = (String)map.get("col"); 
    String word = (String)map.get("word"); 
    int sno =(Integer)map.get("sno"); 
    int eno =(Integer)map.get("eno"); 
 
    System.out.println("sno:"+sno); 
    System.out.print("eno:"+eno); 
    System.out.println("col:"+col); 
 
 
    StringBuffer sql = new StringBuffer(); 
 
    sql.append(" SELECT num, name, subject, to_char(regdate,'YYYY-MM-dd') as regdate, "); 
    sql.append(" count, indent, filename, filesize, r  "); 
    sql.append(" FROM(  "); 
    sql.append("      SELECT num, name, subject, regdate , "); 
    sql.append("    count,  indent, filename, filesize, rownum r "); 
    sql.append("      FROM ( "); 
    sql.append("            SELECT num, name, subject, regdate,  "); 
    sql.append("            count,  indent, filename, filesize "); 
    sql.append("            FROM board "); 
    if(word.length >0 && col.equals("subject_content")){ 
       sql.append("         WHERE (subject LIKE "+"'%"+word+"%' "); 
       sql.append("         OR content LIKE "+"'%"+word+"%') "); 
    }else if(word.length >0){ 
       sql.append("         WHERE "+col+" LIKE "+"'%"+word+"%' "); 
    } 
    sql.append("            ORDER BY ref DESC, ansnum ASC "); 
    sql.append("      ) "); 
    sql.append(" ) "); 
    sql.append(" WHERE r >= ? and r <= ? "); 
 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, sno); 
        pstmt.setInt(2, eno); 
 
 
        rs = pstmt.executeQuery(); 
        while(rs.next()){ 
        BoardDTO dto = new BoardDTO(); 
 
        dto.setNum(rs.getInt("num")); 
        dto.setName(rs.getString("name")); 
        dto.setSubject(rs.getString("subject")); 
        dto.setRegdate(rs.getString("regdate")); 
        dto.setCount(rs.getInt("count")); 
        dto.setIndent(rs.getInt("indent")); 
        dto.setFilename(rs.getString("filename")); 
        dto.setFilesize(rs.getInt("filesize")); 
 
        list.add(dto); 
    } 
 
    }finally{ 
        DBClose.close(pstmt, rs); 
    } 
 
    return list; 
 
} 
/** 
 * 조회수 증가 
 * @param num 
 */ 
public void upCount(int num,Connection con) throws Exception{ 
    PreparedStatement pstmt = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" UPDATE board SET count = count +1 "); 
    sql.append(" WHERE num = ? "); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, num); 
        int cnt = pstmt.executeUpdate(); 
        if(cnt>0){ 
            System.out.println("조회수 증가"); 
        }else{ 
            System.out.println("조회수 증가 실패"); 
        } 
                 
    }finally{ 
        DBClose.close(pstmt); 
    } 
 
} 
/** 
 * 게시판 글보기 
 * @param num 
 * @return 
 */ 
public BoardDTO read(int num,Connection con)  
throws Exception 
{ 
    BoardDTO dto = null; 
    PreparedStatement pstmt = null; 
    ResultSet rs = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" SELECT * from board "); 
    sql.append(" WHERE num = ? "); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, num); 
        rs = pstmt.executeQuery(); 
        if(rs.next()){ 
            dto = new BoardDTO(); 
            dto.setNum(rs.getInt("num")); 
            dto.setName(rs.getString("name")); 
            dto.setSubject(rs.getString("subject")); 
            dto.setContent(rs.getString("content")); 
            dto.setCount(rs.getInt("count")); 
            dto.setFilename(rs.getString("filename")); 
            dto.setFilesize(rs.getInt("filesize")); 
            dto.setRef(rs.getInt("ref")); 
            dto.setIndent(rs.getInt("indent")); 
            dto.setAnsnum(rs.getInt("ansnum")); 
        } 
        
    }finally{ 
        DBClose.close(pstmt, rs); 
    } 
 
    return dto; 
} 
/** 
 * 비밀번호 검사 
 * @param num 
 * @param passwd 
 * @return 
 */ 
public boolean passwdCheck(int num, String passwd,Connection con) 
throws Exception 
{ 
    boolean flag = false; 
    PreparedStatement pstmt = null; 
    ResultSet rs = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" SELECT passwd FROM board "); 
    sql.append(" WHERE num = ? and passwd = ? "); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, num); 
        pstmt.setString(2, passwd); 
        rs = pstmt.executeQuery(); 
        flag = rs.next(); 
    }finally{ 
        DBClose.close(pstmt, rs); 
    } 
 
    return flag; 
} 
 
public boolean update(BoardDTO dto,Connection con)  
throws Exception 
{ 
    boolean flag = false; 
    PreparedStatement pstmt = null; 
    StringBuffer sql = new StringBuffer(); 
 
    try{ 
        int i=0; 
   sql.append(" UPDATE board SET name=?, "); 
   sql.append(" subject=?, content=? "); 
    if(dto.getFilesize()>0){ 
     sql.append(" ,filename= ?, filesize=? "); 
    } 
    sql.append(" WHERE num = ? "); 
 
    pstmt= con.prepareStatement(sql.toString()); 
 
    pstmt.setString(++i, dto.getName()); 
    pstmt.setString(++i, dto.getSubject()); 
    pstmt.setString(++i, dto.getContent()); 
    if(dto.getFilesize()>0){ 
       pstmt.setString(++i, dto.getFilename()); 
       pstmt.setInt(++i, dto.getFilesize()); 
    } 
    pstmt.setInt(++i, dto.getNum()); 
 
    int cnt = pstmt.executeUpdate(); 
    if(cnt>0) flag = true; 
 
    }finally{ 
        DBClose.close(pstmt); 
    } 
 
    return flag; 
} 
/** 
 * ansnum 재정렬 
 * @param ref 
 * @param ansnum 
 */ 
public void upAnsnum(int ref, int ansnum,Connection con) 
throws Exception 
{ 
    PreparedStatement pstmt = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" UPDATE board SET ansnum = ansnum +1 "); 
    sql.append(" WHERE ref = ? and ansnum > ? "); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, ref); 
        pstmt.setInt(2, ansnum); 
        int cnt = pstmt.executeUpdate(); 
        if(cnt>0){ 
            System.out.println("답변이 있으므로 재정렬 "); 
        }else{ 
            System.out.println("답변이 없으므로 재정렬 안됨 "); 
        } 
                 
    }finally{ 
        DBClose.close(pstmt); 
    } 
 
} 
/** 
 * 답변등록 
 * @param dto 
 * @return 
 */ 
public boolean insertReply(BoardDTO dto,Connection con) 
throws Exception 
{ 
    boolean flag = false; 
    PreparedStatement pstmt = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" INSERT INTO board(num, name, passwd, "); 
    sql.append(" subject, content, regdate, ref, indent, ansnum, "); 
    sql.append(" ip, filename, filesize, refnum ) "); 
    sql.append(" VALUES(board_seq.Nextval,?,?,?,?,sysdate,?, "); 
    sql.append(" ?,?,?,?,?,?) "); 
 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setString(1, dto.getName()); 
        pstmt.setString(2, dto.getPasswd()); 
        pstmt.setString(3, dto.getSubject()); 
        pstmt.setString(4, dto.getContent()); 
        pstmt.setInt(5, dto.getRef()); //★ 중요(부모과 같은 ref) 
        pstmt.setInt(6, dto.getIndent()+1);//★ 중요(부모보다 1증가된 indent) 
        pstmt.setInt(7, dto.getAnsnum()+1);//★ 중요(부모보다 1증가된 ansnum) 
        pstmt.setString(8, dto.getIp()); 
        pstmt.setString(9, dto.getFilename()); 
        pstmt.setInt(10, dto.getFilesize()); 
        //부모의 글번호를 refnum에 등록(부모글이 삭제되지 않게하기 위해서) 
        pstmt.setInt(11, dto.getNum()); 
        int cnt = pstmt.executeUpdate(); 
        if(cnt>0) flag = true; 
 
    }finally{ 
        DBClose.close(pstmt); 
    } 
 
    return flag; 
} 
/** 
 * 부모글인지 확인 
 * @param num 
 * @param con  
 * @return 
 */ 
public boolean checkRefnum(int num, Connection con) 
throws Exception 
{ 
    boolean flag = false; 
    PreparedStatement pstmt = null; 
    ResultSet rs = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" SELECT count(*)  FROM board  "); 
    sql.append(" WHERE refnum = ?  "); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, num); 
 
        rs = pstmt.executeQuery(); 
        rs.next(); 
        int cnt = rs.getInt(1); 
        if(cnt>0){ 
           flag = true; //부모글이다 
        } 
    }finally{ 
        DBClose.close(pstmt,rs); 
    } 
 
    return flag; 
    } 
 
/** 
 * 게시판 글 삭제 
 * @param num 
 * @return 
 */ 
public boolean delete(int num, Connection con) throws Exception {
boolean flag = false; 
    PreparedStatement pstmt = null; 
    StringBuffer sql = new StringBuffer(); 
    sql.append(" delete from board  "); 
    sql.append(" WHERE num = ?  "); 
    try{ 
        pstmt = con.prepareStatement(sql.toString()); 
        pstmt.setInt(1, num); 
 
        int cnt =pstmt.executeUpdate(); 
        if(cnt>0){ 
           flag = true; //부모글이다 
        } 
    }finally{ 
        DBClose.close(pstmt); 
    } 
 
    return flag; 
} 
} 

-------------------------------------------------------------------


Missing artifact com.oracle:ojdbc14:jar:10.2.0.4.0 오류

Missing artifact com.oracle:ojdbc14:jar:10.2.0.4.0 


pom.xml에서 


<dependency>

<groupId>com.oracle</groupId>

<artifactId>ojdbc14</artifactId>

<version>10.2.0.4.0</version>

</dependency>


추가 할려고 하면 생기는 오류 

원인은 oracle과 maven 라이센스 문제 떄문에 maven 중앙저장소에서 정보를 받을수 없기 떄문

해결방법

<repositories>
<repository>
<id>mesir-repo</id>
<url>http://mesir.googlecode.com/svn/trunk/mavenrepo</url>
</repository>
</repositories>

문구를 추가해주면 해결 됨


--------------------------------


maven->user settings 


경로 변경





2. 서비스 파일의 생성 확인 


D:/rfid02/spring/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mvc_book/resources 폴더에  


JSP 관련 파일이 통합되어 들어감 






[03] Local 저장소의 변경 



- 메이븐은 기본적으로 저장소를 운영체제의 계정을 따라 생성된다. 

  'C:/Users/STU/.m2' 하지만 이경로는 개발환경이 바뀌면 불편함으로 수동으로 

  저장소를 지정할 수 있다. 


- 기본 경로에있는 jar 파일이 인식이 안되는 경우 인식이됨. 


- 라이브러리를 운영체제로부터 분리하여 이동가능. 



1. Maven 설정 파일의 생성 

>>>>> F:/eGov/spring/maven/settings.xml 

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 

          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 

                              http://maven.apache.org/xsd/settings-1.0.0.xsd"> 

    <localRepository> F:/eGov/spring/maven</localRepository> 

    <interactiveMode>true</interactiveMode> 

    <usePluginRegistry>false</usePluginRegistry> 

    <offline>false</offline> 

    <pluginGroups> 

        <pluginGroup>org.codehaus.mojo</pluginGroup> 

    </pluginGroups> 

</settings> 








































































5. 수업

진도: 

hw: 


6. 할것


spring은 인터넷이 필수인거십니다


'Programming' 카테고리의 다른 글

160531: 54회차  (0) 2016.05.31
160530: 53회차  (0) 2016.05.30
160526: 51회차  (0) 2016.05.26
160525: 50회차  (0) 2016.05.25
160524: 49회차  (0) 2016.05.24
Posted by DAVID
블로그 이미지

by DAVID

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

글 보관함

«   2025/06   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

링크

카테고리

PC (112)
Programming (109)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
DAVID's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

PC

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • PC (112)
    • Programming (109)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바