Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

waitedForU

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

Mvc_Spring

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

Mr.Bini 2016. 5. 27. 10:42

[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/ 

Comments