본문 바로가기

IT/Spring

Spring Annotation 설명 및 예제

먼저 이 글은 갱짱님의 블로그에서

http://gangzzang.tistory.com/130

이 글을 바탕으로 작성 되었음을 알립니다.

(허락 받고 포스팅하게 되었습니다.)

 

 

 

Client가 처리를 요청하는 URL을 던지면,

DispatcherServlet이 이를 받아서 HandlerMapping에 보내고 URL과 매핑되는 Controller가 무엇인지 리턴 받는다.

DispatcherServlet이 이 Controller를 향해 처리를 요청하고 Controller는 요청받은 일을 처리하고, ModelAndView를 리턴한다.

그럼 DispatcherServletViewResolver에게 실행결과의 View를 요청하고,

ViewResolver는 실행결과의 View를 리턴한다.

그럼 DispatcherServlet은 이를 통해 생성출력을 View에게 요청하고

View JSP를 생성하여 클라이언트에게 돌려준다.

 

DispatcherServlet

Client의 요청을 받아 요청에 맞는 controller가 리턴한 결과를 view에 전달

HandlerMapping

Client의 요청 URL에 맞는 Controller를 결정해줌

Controller

Client의 요청을 처리한 후, 결과를 dispatcherservlet에 리턴(요청한 작업이 일어 나는 곳인듯.)

ModelAndView

Controller가 처리한 결과 및 view에 필요한 정보를 담음 (잘 모르겠음)

ViewResolver

Controller 처리결과를 생성할 view를 결정함.

View

Controller의 처리 결과 화면을 만듦.

1.     Client에게 요청을 받을 DispatcherServlet web.xml파일에 설정한다. ß web에서 Dispatcherservlet을 선언한다는 얘긴데

2.     Client에게 받은 요청을 처리할 Controller을 만듦.

3.     ViewResolver 설정

4.     JSP 등을 이용한 view 코드

 

1.     <Servlet> 태그를 이용하여 dispatcherservlet을 설정함.

<servlet-mapping>을 이용해서 요청되는 URL패턴들을 설정. 어떻게 들어오는 것들을 controller로 넘길 것인지.

<!--?xml version="1.0" encoding="UTF-8"?-->

<web-app id="WebApp_ID" xmlns="http://java.sun.com/xml/ns/javaee" version="3.0" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <display-name>Spring</display-name>

     <servlet>

        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    </servlet>

 

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>

</web-app>

 

2.     Controller 구현 및 설정 추가.

@Controller Annotation을 클래스에 적용.

@RequestMapping Annotation을 이용해 클라이언트의 요청을 처리할 method 지정.

Modelandview controller의 처리 결과를 보여줄 view view에서 출력할 model을 지정.

@Controller

public class HelloController {

         @RequestMapping("/hello.do")

        public ModelAndView hello() {

            ModelAndView mv = new ModelAndView();

            mv.setViewName("hello"); ß view name setting.

            mv.addObject("message", "Hello Spring MVC");

            return mv;

        }

}

Dispatcherservlet spring container에서 Controller objeect를 검색함. 따라서, spring에서 dispatcherservlet이 돌아가게 하려면, spring설정 파일에 Controller 디렉터리를 bean으로 등록해야함.

<!--?xml version="1.0" encoding="UTF-8"?-->

<!-- dispatcher-servlet.xml -->

<beans xmlns="http://www.springframework.org/schema/beans" 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" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context">

<bean class="com.~~.HelloController" id="helloController"></bean>

</beans>

3.     ViewResolver 설정 추가하기.

컨트롤러에서 modelandview.setviewname() ß method를 통해 view 이름 설정. view이름과 mapping view 구현체를 찾기위해 viewresolver 사용. Prefix suffix 지정.

앞의 예제에서 setviewname을 통해 hello라는 view name을 세팅했다.

<!--?xml version="1.0" encoding="UTF-8"?-->

<!-- dispatcher-servlet.xml -->

<beans xmlns="http://www.springframework.org/schema/beans" 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" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context">

    <bean class="com.~~.HelloController"id="helloController"></bean>

     ( ^위에서 설정한, controller^ )

<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">

        <property value="/WEB-INF/view/" name="prefix"></property>

        <property value=".jsp" name="suffix"></property>

    </bean>

</beans>

 

View 구현

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>${ message }</title>

</head>

<body>

${ message }

</body>

</html>

 


1.     Dispatcherservlet설정과 applicationcontext의 관계

Web.xml 파일에 여러 개의 dispatcherServlet을 설정할 수 있음.

그리고 dispatcherservlet한 개당 한 개의 webapplicationcontext를 가짐.

 

[설명해줄게]

Dispatcherservlet은 기본적으로 /web-inf/에 위치한 [서블릿이름]-servlet.xml 파일에서 스프링 설정 정보를 읽어온단 말야. 그래서, 한 개 이상의 설정파일이나, 다른 이름의 설정 파일을 사용하게 되면, ContextConfigLocation init-param에 설정파일 목록을 지정해야하는거야. 설정정보들의 위치를 알려주는거지. 그래서 위에 사용한 소스들을 가져와서 수정해보자면,

 

<!--?xml version="1.0" encoding="UTF-8"?-->

<web-app id="WebApp_ID" xmlns="http://java.sun.com/xml/ns/javaee" version="3.0" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

     <servlet>

        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

         <init-param>

              <param-name>contextConfigLocation</param-name>

              <param-value>

                     /WEB-INF/beans.xml

                     /WEB-INF/main.xml

              </param-value>

         </init-param>

</servlet>

 

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>

</web-app>

 

<init-param> 보라색으로 표시된 부분이 설정파일들을 알려주는 부분이다. 그래서

<param-name>에서 contextConfigLocation 이라고 선언하였고,

<param-value>에서 설정파일들의 location을 명시하여주었다.

설정파일의 리스트는 콤마, 공백, , 줄바꿈 세미콜론으로 구분한다.

 


 

다음은 ApplicationContext 설정에 관한 부분이다.

한 개 이상의 dispatcherservlet을 사용할 때 별도의 WebApplicationContext를 생성해야한다고 한다.

공통의 빈이 필요할 경우 ContextLoaderListener를 사용하여 사용될 빈을 설정한다.

servletListener로 등록, contextConfigLocation context-param을 이용하여, 공통으로 사용될 bean 정보를 담고 있는 설정 파일 목록을 지정해준다.

contextLoaderListener가 생성하는 WebApplicationContext WebApplication root context이다. 그리고 Dispatcherservlet이 생성하는 WebapplicationContext root context parent로 받는 child context이다.

ContextLoaderListenercontextConfigLocation 을 통해 <context-param>을 명시하지 않으면, /WEB-INF/applicationContext.xml을 설정 파일로 사용하게 된다.

 

<!--?xml version="1.0" encoding="UTF-8"?-->

<!-- web.xml -->

<web-app id="WebApp_ID" xmlns="http://java.sun.com/xml/ns/javaee" version="3.0" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!--

    <servlet>

        <servlet-name>front_dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>/WEB-INF/front.xml</param-value>

        </init-param>

    </servlet>

     

    <servlet>

        <servlet-name>rest_dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>/WEB-INF/rest.xml</param-value>

        </init-param>

    </servlet>

    -->

     

    <context-param>

        <param-name>contextConfigLocation</param-name> ß 이것을 명시함으로써, /WEB-INF/applicationContext.xml이 아닌 front.xml&service.xml을 참고하게 됨.

        <param-value>

            /WEB-INF/front.xml

            /WEB-INF/service.xml

        </param-value>

    </context-param>

 

    <listener> ß 공통의 bean이 필요한 경우에 선언되는 것인데 (솔직히 잘 모르겠음)

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

그리고 이 부분 (ContextLoaderListener)가 선언 된 부분이 root WebApplicationContext가 되는 것 같구

이 아래 부분 (DispatcherServlet)이 생성하는 부분은 아마도, root webapplicationcontext를 상속받아 생성 되는 것 같아. 확실힌 모르겠어..

    <servlet>

        <servlet-name>front</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    </servlet>

     

    <servlet>

        <servlet-name>rest</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    </servlet>

     

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>

</web-app>

 

그러니까, 내 생각엔말야.

제일 위에 <context-param>을 통해서 contextConfigLocation을 선언시키면서 context 파일들을 지정해주고.

<Listener>는 잘 모르겠구 아마 parent라서 ?몰라.

그리고 아래에선 <servlet>을 선언해주는 뭐 그런건가?

근데 servlet에서 각각 init-param을 지정하는 것이 아니라. 위에 선언한 것을 상속받아서 사용되기에 딱 servlet -class까지만 선안하는 거 보니 코드가 더 보기 좋아지긴 했어.


 

 

<servlet>

 <servlet-name>front_dispatcher</servlet-name>

 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  <init-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>/WEB-INF/front.xml</param-value>

  </init-param>

</servlet>

     

 

<servlet>

 <servlet-name>reset_dispatcher</servlet-name>

 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  <init-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>/WEB-INF/front.xml</param-value>

  </init-param>

</servlet>

 

 

Front reset 빼고 똑같음.

 <context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>

            /WEB-INF/front.xml

            /WEB-INF/service.xml

    </param-value>

 </context-param>

 

<listener>

 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

     

<servlet>

  <servlet-name>front</servlet-name>

  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

</servlet>

     

<servlet>

   <servlet-name>rest</servlet-name>

   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

</servlet>

     

<servlet-mapping>

  <servlet-name>dispatcher</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

 

중복이 매우 적음.

그래서 쓰는 듯.

 

다음은, 캐릭터 인코딩 처리 필터 부분. 모든 controller에서 responses.setCharacterEncoding()을 실행하는 번거로움을 극복하기 위해, servlet에서 filter 처리를 해준다.

Servlet filter에서 CharacterEncodingFilter class를 제공해주거든.

<!--?xml version="1.0" encoding="UTF-8"?-->

<!-- web.xml -->

<web-app id="WebApp_ID" xmlns="http://java.sun.com/xml/ns/javaee" version="3.0" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<servlet>

    <servlet-name>dispathcer</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

</servlet>

 

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

 

<servlet-mapping>

    <servlet-name>dispatcher</servlet-name>

    <url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

 

. 드디어 controller.

 

@controller, @RequestMapping Annotation에 대해서 알아보자.

 

Controller class @Controller Annotation 적용

Client의 요청을 처리할 method @RequestMapping Annotaion 적ㅇ요

 

@RequestMapping Annotation은 해당 Method에서 처리할 URL을 값으로 가짐

@RequestMapping Annotation이 선언된 method return type은 상황에 따라 알맞은 타입으로 선언.

 

Controller Method HTTP 전송방식

-       하나의 요청 URL에 대해 HTTP GET, POST를 한 개의 controller에서 처리할 경우

-       @RequestMapping Annotation method 속성을 이용해서 method가 처리할 HTTP method를 제한.

// HelloController2.java

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

@Controller

@RequestMapping("/write.do") ß method가 선언안되면, HTTP(GET,POST,DELETE,PUT)모두 처리

public class HelloController2 {

 

        @RequestMapping(method=RequestMethod.GET) ß get

        public String writeForm() {

            return "writeForm";

        }

         

        @RequestMapping(method=RequestMethod.POST) ß post

        public String writeSub() {

            return "writeSub";

        }

}

 


 

HTML form, command object

 

HTML form에 입력한 data javabean obejct를 이용해서 전달 받음.

HTML 폼의 항목 이름과 javabean class property 이름이 일치할 경우 form에 입력한 값을 property 값으로 설정함.

@RequestMapping Annotation이 적용된 method parameter javabean type 추가.

Form에 입력한 값은 모두 문자열이지만, spring javabean type 변환 처리 기능으로 property type으로 알맞게 변환

 

HTML form(writeForm.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WriteForm</title>
</head>
<body>
<form action="write.do" method="post">
    <input type="text" name="name" placeholder=" 이름" required="required" size="50"><br>
<input type="text" name="manufacturer" placeholder=" 제조사" required="required" size="50"><br>
<input type="text" name="price" placeholder=" 가격" required="required" size="50"><br>
<input type="submit" value="작성"><input type="reset" value="취소">
</form>
</body>
</html>

 

Javabean(PhoneDTO.java)

public class PhoneDTO {

    private String name;

    private String manufacturer;

    private int price;

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getManufacturer() {

        return manufacturer;

    }

    public void setManufacturer(String manufacturer) {

        this.manufacturer = manufacturer;

    }

    public int getPrice() {

        return price;

    }

    public void setPrice(int price) {

        this.price = price;

    }

}

 


 

 

Controller(PhoneController.java)

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

import com.~~.PhoneDTO;

 

@Controller

public class PhoneController {

 

    @RequestMapping(value = "/write.do", method = RequestMethod.GET)

    public String writeForm() {

        return "writeForm";

    }

 

    @RequestMapping(value = "/write.do", method = RequestMethod.POST)

    public String wirteSubmit(PhoneDTO phoneDTO) {

        return "writeSubmit";

    }

}

 

 

view에서 command object 접근

 

(wirteSubmit.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>WriteSubmit</title>

</head>

<body>

  <input type="text" name="name" placeholder=" 이름" required="required" readonly="readonly" size="50" value="${ phoneDTO.name }"><br>

  <input type="text" name="manufacturer" placeholder=" 제조사" required="required" readonly="readonly" size="50" value="${ phoneDTO.manufacturer }"><br>

  <input type="text" name="price" placeholder=" 가격" required="required" readonly="readonly" size="50" value="${ phoneDTO.price }"><br>

</body>

</html>

 

 

 

 

 

 

 

 

 


 

뷰에서 사용할 모델 이름을 변경할 때엔 @ModelAttribute Annotation을 이용하고, command object model이름을 지정한다.

 

(PhoneController.java)

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

import com.tistory.gangzzang.model.PhoneDTO;

 

@Controller

public class PhoneController {

 

    @RequestMapping(value = "write.do", method = RequestMethod.GET)

    public String writeForm() {

        return "writeForm";

    }

 

    @RequestMapping(value = "write.do", method = RequestMethod.POST)

    public String wirteSubmit(@ModelAttribute("p") PhoneDTO phoneDTO) {

        return "writeSubmit";

    }

}

위와 같이 controller를 수정하면

 

view에선

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>WriteSubmit</title>

</head>

<body>

         <input type="text" placeholder=" 이름" required="required" readonly="readonly" size="50" value="${ p.name }"><br>

         <input type="text" placeholder=" 제조사" required="required" readonly="readonly" size="50" value="${ p.manufacturer }"><br>

         <input type="text" placeholder=" 가격" required="required" readonly="readonly" size="50" value="${ p.price }"><br>

</body>

</html>

p.smt으로 value를 읽어올 수 있다.

 


 

Command object -> list로 받기

 

PhoneVo.java

import java.util.List;

 

public class PhoneVO {

    private List<PhoneDTO> phoneItems;

 

    public List<PhoneDTO> getPhoneItems() {

        return phoneItems;

    }

 

    public void setPhoneItems(List<PhoneDTO> phoneItems) {

        this.phoneItems = phoneItems;

    }

}

 

wirteListForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WriteListForm</title>
</head>
<body>
<form action="writeList.do" method="post">
<input type="text" name="phoneItems[0].name" placeholder=" 이름1" required="required" size="50"><br>
<input type="text" name="phoneItems[0].manufacturer" placeholder=" 제조사1" required="required" size="50"><br>
<input type="text" name="phoneItems[0].price" placeholder=" 가격1" required="required" size="50"><br>
<hr>
 
 
<input type="text" name="phoneItems[1].name" placeholder=" 이름2" required="required" size="50"><br>
<input type="text" name="phoneItems[1].manufacturer" placeholder=" 제조사2" required="required" size="50"><br>
<input type="text" name="phoneItems[1].price" placeholder=" 가격2" required="required" size="50"><br>
<hr>
<input type="submit" value="작성"><input type="reset" value="취소">
</form>
</body>
</html>

 

PhoneController.java

@Controller

public class PhoneController {

   @RequestMapping(value = "writeList.do", method = RequestMethod.GET)

    public String writeListForm() {

        return "writeListForm";

    }

    @RequestMapping(value = "writeList.do", method = RequestMethod.POST)

    public String wirteListSubmit(@ModelAttribute("phone") PhoneVO phoneVO) {

        return "writeListSubmit";

    }

다음은, Controller method parameter type이다.

Controller @RequestMapping Annotation이 적용된 method command class 외에도 다양한 type parameter를 가질 수 있음.

 

@RequestParam Annotation

HTTP 요청 parameter method parameter로 전달 받을 때 사용.

Annotation이 적용된 parameter String이 아닐 경우 실제 type에 따라 알맞게 type 변환 수행

필수가 아닌 parameter인 경우 required 속성값을 false로 지정(기본값 true)

필수가 아닌 parameter의 경우 defaultvalue 속성 값으로 기본값을 지정.

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

 

@Controller

public class ParamController {

 

        @RequestMapping(value = "param.do", method = RequestMethod.GET)

        public String param(

                @RequestParam(value="name", required=false) String name,

                @RequestParam(value="age", defaultValue="1") int age) {

            return "param";

        }

}

 

@CookieValue Annotation 이용 Cookie Mapping

Cookievalue parameter로 전달 받을 때 사용.

해당 cookie가 존재하지 않으면 500에러 코드 전송

쿠키가 필수가 아닌 경우 required 속성값을 위와 같이 지정

쿠키가 필수가 아닌 경우 defaultvalue 속성값으로 기본값 지정.

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

 

@Controller

public class cookiecontroller{

 

        @RequestMapping(value = "cookie.do", method = RequestMethod.GET)

        public String cookie(

                @RequestParam(value="name", required=false) String name,

                @RequestParam(value="age", defaultValue="1") int age) {

            return "cookie";

        }

}

 


 

@RequestHeader annotation 이용 header mapping

HTTP 요청 Header의 값을 method parameter로 전달 받을 때 사용.

해당 헤더가 존재하지 않으면 500에러코드 전송

Required 속성과 defaultValue 속성을 위와 같이 사용.

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CookieValue;

import org.springframework.web.bind.annotation.RequestHeader;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

@Controller

public class HeaderController {

    @RequestMapping(value = "header.do", method = RequestMethod.GET)

    public String header(

            @RequestHeader(value="Accept-Language", required=false) String languageHeader,

            @RequestHeader(value="user-agent", defaultValue="모름") String agentHeader) {

        return "header";

    }

}

 

 

서블릿 API 직접사용

- javax.servlet.http.HttpServletRequest / javax.servlet.ServletRequest

- javax.servelt.http.HttpServletResponse / javax.servlet.ServletResponse

- javax.servlet.http.HttpSession

- 스프링 MVC 제공 애노테이션을 이용 정보(파라미터, 헤더, 쿠키, 세션 등)에 접근 할 수 있기 때문에 직접적으로 서블릿 API를 사용해야 하는 경우는 드뭄

- 세가지 경우에 사용(HttpSession의 생성을 직접 제어, 컨트롤러에서 쿠키를 생성, 서블릿 API 사용을 선호)

 

Controller method return type

Modelandview: view정보 및 model 정보를 담고있는 modelandview객체

Model : view에 전달할 객체정보를 담고 있는 model return, view 이름은 요청 url로부터 결정(requestToViewNameTranslator를 통해 결정)

Map : view에 전달할 객체 정보를 담고 있는 map return, view 이름은 요청 url로부터 결정 (상동)

String : view 이름을 return

View 객체 : view 객체를 직접 return, 해당 view 객체를 이용해서 view를 생성

Void : method servletResponse HttpServletresponse type parameter를 갖는 경우 method가 직접 응답을 처리한다고 가정, 그렇지 않을 경우 요청 view 이름은 요청 url로부터 결정.

@responsebody : method에서 @responseBody Annotation이 적용된 경우 return 객체를 HTTP응답으로 전송, HttpMessageConverter릴 용해서 객체를 HTTP응답 스트림으로 변화.

 

Controller class auto scan

@Controller Annotation @component annotation과 마찬가지로 component scan 대상

<contetxtcompoent-scan> 태그를 이용 컨트롤러 클래스를 자동으로 로딩

Base-package 속성에 자동스캔할 패키지 경로를 입력

복수의 패키지를 사용하고 싶은 경우 <contextcomponent-scan>태그를 복수개 작성

<beans xmlns="http://www.springframework.org/schema/beans" 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" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context">

 

    <context:component-scan base-package="com.~~.controller"></context:component-scan>

</beans>

 

 

 

'IT > Spring' 카테고리의 다른 글

Spring MVC 예제  (0) 2015.01.30
Spring에서 excel 사용하기 JXL & POI 개념 및 예제  (2) 2015.01.23
Spring JDBC framework 개념 및 예제  (0) 2015.01.22
Spring-IOC (DI) 개념 및 예제  (2) 2015.01.21
Spring 이론  (0) 2015.01.20