스프링 @MVC의 편리함과 유연함은 지금까지 나온 어떤 MVC 방식의 프레임워크와 기술도 따라 올 수 없는 것이라고 생각한다. Controller의 계층구조에 존재했던 각종 컨트롤러 클래스들의 장점을 모두 모으고, 몇 배로 편리하게 사용할 수 있도록 만들어 놓은 것이 지금의 @MVC이다.

간단히 정리해보고 싶은 것은 @MVC의 컨트롤러 메소드에서 리턴하는 모델과 뷰 정보에 스프링이 자동으로 추가해주는 정보들이다. @MVC는 매번 번거롭게 ModelAndView를 만들어 리턴하지 않아도 되도록, 간단히 뷰 이름, 모델 맵, 단독 모델 오브젝트 등의 리턴 타입을 허용한다. 이 때 다음 4가지 종류의 오브젝트는 모델에 자동으로 추가된다.

1. @ModelAttribute 또는 커맨드 오브젝트

@MVC 메소드는 String add(@ModelAttribute User user) 또는 String add(User user) 라고 빈 스타일의 오브젝트를 통해서 파라미터나 폼 데이터를 전달 받을 수 있다. 보통 후자는 전통적인 이름을 따서 커맨드 오브젝트라고 부르고, 전자는 모델 애트리뷰트라고 부르지만 사실 내부적으로는 똑 같이 취급된다.

이 모델 애트리뷰트/커맨드 오브젝트는 자동으로 모델 맵에 추가된다. 따라서 따로 모델에 넣어줄 필요가 없다.

2. Map/Model/ModelMap

메소드 파라미터에 위의 세가지 중 한가지 타입을 넣었다면 모델 맵을 따로 생성할 것 없이 파라미터로 받은 오브젝트에 직접 모델을 추가해주면 된다. 당연하게도 이 파라미터에 넣은 모델 오브젝트는 컨트롤러가 리턴하는 모델이 된다. 흥미로운 점은 만약 메소드에서 리턴 값을 ModelAndView나 Model, 또는 단독 모델 오브젝트(String 타입이 아닌 단순 오브젝트는 그 자체로 하나의 모델 값으로 인식된다) 같은 것을 써서 모델 정보를 리턴한다고 하더라도, 이 파라미터 모델 맵의 정보가 무시되는 것이 아니다. 모두 최종적인 모델에 머징된다.

3. @ModelAttribute 메소드

MVC 시절 referenceData() 메소드와 같은 역할을 하는 @ModelAttribute를 메소드 레벨에 부여한 메소드가 있다면 그 결과 값은 항상 나머지 모든 컨트롤러 메소드의 모델에 자동 추가된다. 보통 참조용 데이터, 예를 들면 리스트박스에 뿌리는 코드 값 같은 것에 주로 사용된다.

4. BindResult.모델 이름의 BeanPropertyBindingResult

만약 @ModelAttribute를 명시적으로 또는 암시적으로 사용했다면 모델에는 자동으로 그 바인딩 결과가 담긴 "org.springframework.validation.BindingResult.모델이름"의 오브젝트가 추가된다. 타입은 BeanPropertyBindingResult이다. 이 모델은 스프링의 폼 태그에서 바인딩 결과에 따라서 메시지를 출력하거나 할 때 참조하기 위해서 자동으로 넣어주는 것이다.

컨트롤러 메소드에 Errors나 BindResult 파라미터를 넣었는지 여부와는 상관없이 이 모델은 추가된다.

 

모델 말고 뷰도 생각해 보자면, 뷰 정보를 전혀 생성하지 않았을 경우에는 RequestToViewNameResolver 전략이 적용되서 자동으로 뷰 이름이 생성된다.

오늘의 퀴즈. 다음 메소드를 실행하고 나서 DispatcherSerlvet이나 뷰가 전달 받는 모델 맵에는 몇 개의 엔트리가 있을까?

 

@ModelAttribute(“ref”) String ref() { return “data”;}

@RequestMapping(“/add”) public void add(User user, Model model) {

   model.addAttribute(“mesg”, "ok”);

}

 

정답을 맞추면… 보너스를.

Related posts:

  1. Spring Expressions(SpEL)를 이용한 Mockito Argument Matcher 만들기
  2. Spring 3.0 (41) @Deprecated SpringMVC
  3. Spring 3.0 (26) Spring Expression Language와 @Value
  4. [토스3] 스프링 JDBC DAO에 lazy-loading 적용하기 (2)
  5. Spring 3.0 (8) Core 모듈의 선택 라이브러리 분석
  6. Spring 3.0 (52) 반쪽짜리 3.0 RC1 공개
  7. Spring 3.0 (14) Context Support 모듈의 선택 라이브러리 분석
  8. Inside Spring (5) PropertyPlaceholderConfigurer를 @Bean으로 정의해서는 안되는 이유
  9. Spring 3.0 (37) 스프링 모듈-라이브러리 의존관계 매트릭스 업데이트와 CTDD
  10. Spring 3.0 EL (Spel)을 이용한 AssertThrows 확장 (3)
  11. Spring 3.0 (53) Spring Dependency Matrix 업데이트
  12. Spring 3.0 (35) Spring 3.0 Reference Document 공개
  13. Spring 상식퀴즈 (1) – DI 태클하기
  14. [토스3] 스프링 JDBC DAO에 lazy-loading 기능 적용하기
  15. Spring 3.0 (7) Spring 3.0 Dependency Matrix

Facebook comments:

to “Spring 3.0 @MVC 메소드에서 자동으로 리턴 모델에 추가되는 것들”

  1. 답을 다 알려주시고 맞추라고 하시다니..ㄷㄷㄷㄷ;;;
    저는 열외인가요. 저도 보너스를… (퍽..퍽퍽.. 어서 백업 프로그램이나 만들께요;;)

  2. 답은 4~
    ref=”", user=”", “mseg”=”", org.springframework.validation.BindingResult.user=…

    틀려도 참가상 같은거 있죠?

  3. 난 찬욱님 편~~~ -_-);

  4. 앗.. 찬욱님 답에 mseg아니고 mesg같은…. ㅎㅎ

  5. buy ambien ambien cr mechanism of action – what is ambien high like

  6. cz7eDq pepqumiefeug, [url=http://pgqdopyckjgw.com/]pgqdopyckjgw[/url], [link=http://xmxwirzhtdpr.com/]xmxwirzhtdpr[/link], http://wpvjrgeoczfk.com/

  7. An outstanding share! I have just fοrwardeԁ
    thіs onto a co-wοrkeг who hаs bеen doіng a little homewогκ on this.
    And he actuаlly ordеreԁ me breaκfast due tо the fасt that ӏ diѕcoѵereԁ it fοr him.
    .. lol. So lеt me rewoгԁ
    thіѕ…. Thanks for thе mеal!
    ! But yeah, thanx foг spendіng the time to diѕcuѕs this
    issue hеrе оn уоur intеrnet ѕіte.

  8. Thank you fоr anotheг informative website. Thе
    plаce еlse maу I get that type οf info written іn such a ρerfeсt method?
    I hаve a proϳect that I’m just now working on, and I’ve been on
    the glanсe out for suсh infoгmation.

    Feel free to surf to my weblog – Daniel Chavez Moran

  9. Good post. I learn something new and challenging on sites
    I stumbleupon everyday. It will always be interesting to read content from other authors and practice a little something from their
    sites.

  10. , Is Muscle Maximizer a sham or does it sincerely work.

    The 62 page Somanabolic Weight Training program that details the specific workouts
    you need to do depending on your somatotype (body type) in order to pack on lean muscle mass.

    In his new program Kyle Leon offers high quality information and
    offers a proven muscle building system that has been designed by renowned fitness models from around the
    world that have been adjusted and tested for a long time in order to provide
    the best results.

    My web page – Somanabolic Muscle Maximizer Review

  11. The program comes with full warranty 60 days money back, so everyone can actually try this
    muscle building system for a few weeks and see the results without any risk at all.
    Yes we would like muscle, but in the right
    way, and gaining lean muscle without fat is the key to doing this.

    Then opt for ones cheapest way to help you feed those guns while using the Egg White peptids.

    Also visit my site … somanabolic muscle maximizer review

  12. Great post. I was checking continuously this blog and I
    am impressed! Extremely helpful information specifically the last part :) I care for such information a lot.
    I was seeking this certain information for a long time.
    Thank you and good luck.

  13. Hi there, You have done a great job. I’ll certainly digg it and personally recommend to my friends. I’m
    sure they will be benefited from this site.

  14. Admiring the dedication you put into your site and detailed information
    you offer. It’s great to come across a blog every once in a while that isn’t
    the same outdated rehashed material. Fantastic read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  15. I’ve read a few just right stuff here. Certainly worth bookmarking for revisiting. I wonder how so much effort you set to make this kind of wonderful informative website.

  16. Everyone loves it when folks get together and share views.
    Great site, continue the good work!

  17. I’ve been exploring for a bit for any high quality articles or weblog posts in this kind of space . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i am satisfied to show that I’ve a very good uncanny feeling I came
    upon exactly what I needed. I most undoubtedly will make
    sure to do not forget this web site and provides
    it a look regularly.

  18. Thanks for your marvelous posting! I genuinely enjoyed reading it, you may be a great author.
    I will make certain to bookmark your blog and may come back in the foreseeable future.
    I want to encourage you to continue your great job, have a nice evening!

  19. No matter if some one searches for his vital thing, thus
    he/she desires to be available that in detail, therefore that thing
    is maintained over here.

  20. Most peоple who have neeԁed to engage the serviсes of a prіvate detеctive аnԁ іnvestigator in Neω Zeаland you
    muѕt fiгst apрly for a lіcеnsе.
    Victorу Inѵеstigations is THE source for investigative services
    and also beneficial for you as he/she can hеlp
    you to know that what аre the elements that агe necesѕarу in order to obtaіn mоre іnformation.

    mу web blog; bο dietl (http://quizilla.teennick.com)

  21. This software helps you customize nutrition
    dependant on your real age, weight, height, and metabolism.

    To find out if it is actually true and to understand better if Kyle Leon’s system is generally for you or not, let’s look into a few of the benefits and drawbacks of the product.
    this program developer, Kyle Leon, is a well-known personal trainer and nutrition expert in
    recent years and is regarded as one of the most respected coaches in the world when it
    comes to building muscle mass naturally.

    Feel free to visit my webpage Somanabolic Muscle Maximizer Review

  22. - The flat surface has to be cleaned and if still there is
    a need, Arctic Silver 5 Compound can be purchased and used.

    Having said that this just isn’t a predetermined amount and this specific number is definitely rising day by day.
    Just make sure that you own the original copy and will not sell or give away the
    backup copies to anyone in any way possible because this is an act of piracy.

  23. Howdy! This blog post couldn’t be written any better! Looking at this article reminds me of
    my previous roommate! He always kept preaching about this.
    I most certainly will forward this information
    to him. Pretty sure he will have a very good read. Thanks for sharing!

  24. My spouse and I absolutely love your blog and find a lot of
    your post’s to be what precisely I’m looking for. can you offer
    guest writers to write content in your case?
    I wouldn’t mind creating a post or elaborating on a lot of
    the subjects you write regarding here. Again, awesome web site!

  25. I don’t know whether it’s just me or if perhaps everyone else encountering problems with your blog.
    It appears like some of the text within your content
    are running off the screen. Can someone else please comment
    and let me know if this is happening to them as well?
    This may be a problem with my web browser because I’ve had this
    happen before. Thanks

  26. If you are going for best contents like myself, simply visit this web page daily for the reason that it presents feature
    contents, thanks

  27. This blog was… how do I say it? Relevant!! Finally I’ve found something
    which helped me. Thank you!

  28. What’s up, I want to subscribe for this web site to obtain most up-to-date updates, so where can i do
    it please help out.

  29. Hey There. I found your blog the use of msn. This is a very
    smartly written article. I will be sure to bookmark
    it and return to learn more of your helpful info. Thanks for
    the post. I’ll definitely return.

  30. Hello there, You have done an excellent job. I’ll certainly digg it and personally recommend
    to my friends. I’m sure they will be benefited from this site.

  31. Great post. I used to be checking constantly thiѕ blog аnd I’m inspired!

    Very useful informаtiοn specifically the final
    part :) I cаrе for ѕuch info much.
    I used to be looκing for this ceгtaіn іnfo for a ѵery lengthy
    time. Thanks and best of luck.

    Herе iѕ my web page levis sklep (Mervin)

  32. I am sure this piece of writing has touched all
    the internet people, its really really pleasant post on building up new website.

  33. Attractive part of content. I just stumbled upon your site and in accession
    capital to claim that I get in fact loved account your weblog posts.
    Anyway I will be subscribing for your augment and even
    I success you get entry to constantly quickly.

  34. Hi there everyone, it’s my first pay a visit at this website,
    and piece of writing is in fact fruitful in support of me,
    keep up posting these articles.

  35. Greetings from California! I’m bored to death at
    work so I decided to check out your website on my iphone during lunch break.
    I really like the information you provide here and can’t
    wait to take a look when I get home. I’m shocked at how fast your blog loaded on my cell phone ..
    I’m not even using WIFI, just 3G .. Anyways, excellent blog!

  36. Outstanding post however I was wondering if you could
    write a litte more on this topic? I’d be very grateful if you could elaborate
    a little bit more. Kudos!

  37. There are other affordable coins that make good investments.

    Try to let the sauce cool down a bit before placing it on the pizza.
    Tour Marvel Cave just as the early explorers did – by lantern
    light.

  38. Over the past 5 years it is more than fair to say that wages
    have not increased, in fact many people have had to take a pay cut, and
    the cost of living has certainly increased.
    Today plating does not require any actual gold, just a solution
    containing gold salts. Gold bullion bars for IRA must be of a minimum purity of 99.

  39. The more you can spread out your sources of income the better
    protected you’ll be if something happens to one of your accounts or revenues streams.
    The property can be rented out with the income earned going
    back to the account. For the reason that someone can avoid the
    minimum distribution, it is able to produce huge tax savings and let the owners to
    acquire greater wealth from now on years.

  40. The RMDs must begin in the year after the year of
    the original owner’s death. So if you want to obtain any of these discounted properties, you can then have your IRA invest in real estate.
    First thing that you need to do is determine on how you want to invest since this will require
    due diligence just like any other type of investment.

  41. This may also depend on the chemical sensitivity, genetic disposition, and predisposing
    health history. In addition, check behind walls, under cabinets, and
    under carpeting as well as air ducts. On the other hand, as the oral chelator DMSA
    removes mercury from the brain.

  42. Even more powerful than those found in berries and grapes, green tea anti-oxidants work like magic at ridding your body of free
    radicals (toxins). Items containing refined flour (like biscuits, cakes, white bread or pasta) should be taken
    at the minimum. The soap making kit you have gives you more confidence that the product will be as perfect as what you expected it to turn
    out.

  43. Preservatives, methylparaben in particular, have been shown to increase the skin
    damage caused by UV light, thus increasing the aging of the
    skin. Nerve site ‘potentiators’ are being used in significant amounts as are ‘relatives’ of neurotransmitter precursors and a host of
    very powerful and complex compounds many inducing a
    ‘feel – good’ factor in fish. On the other hand, as the oral
    chelator DMSA removes mercury from the brain.

  44. The console will be initially released in either Black or Blue and some of the
    games that will be released for the launch of the console include Mario Kart 3DS, PES 2011 3DS, Ridge Racer
    3D and The Sims 3. But to guard your valued gadget, you need the very best Nintendo 3DS accessories.
    The 3DS camera is actually two outer 3DS cameras which you can take 3D photos with, and
    there are a variety of lenses (such as Pinhole lens and Merge lens) to use to make some cool pictures with.

  45. mens mbt shoes Spring 3.0 @MVC 메소드에서 자동으로 리턴 모델에 추가되는 것들 » Toby’s Epril

  46. chung shi Spring 3.0 @MVC 메소드에서 자동으로 리턴 모델에 추가되는 것들 » Toby’s Epril

  47. Your positive example could even induce some of them to choose sustainable
    house design. The two major benefits of taking organic tea are -.
    Look for the FSC endorsement to ensure your provider will print green.

  48. I’m excited to uncover this web site. I wanted to thank you for ones
    time for this wonderful read!! I definitely savored
    every bit of it and I have you book marked to see new things
    in your web site.

  49. (This is aside from their common uses similar
    to that of the Roman civilization. Discover the healthful
    benefits of goat milk products. These xenoestrogens (“foreign estrogens”) remain active for
    a much longer than natural time, letting them proliferate continuously and wreak havoc on the body.

  50. The test covers all aspects of work with dangerous substances.
    The majority of nations existing under this globe are dotted with factories that
    keep manufacturing numerous products and materials throughout the year.
    Now, less than three years later, look where we are.

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2017 Toby's Epril Suffusion theme by Sayontan Sinha