Spring MVC

MVC: Model, View, Control.
DispatcherServlet is the core of Spring MVC. Accept requests from clients, and give response.
In Web MVC, based on request-response model, Model can not push data to View, which should be via Controller. Controller is the dispatcher. While in standard MVC, Model can pass data to View positively.


1. Annotation on ccontroller

@RequestMapping
An annotation to map request url to related method of controller.
You can mark it on class name or methods' name.
Support regex match. The placeholder has been added since Spring 3.0.

@RequestMapping("/user/login")    // @RequestMapping(value="/user/login")
 /user/*/login:    /user/aa/login,     /user/b/login,    ... 
/user/**/login:     /user/login,     /user/aaa/bbb/login,    ...
/user/login??:    /user/loginaa,    /user/loginbb, ...
/user/{usrId}:    /user/123, ...

The placeholder can be bound to params of methods by @PathVariable("xxx").

@Controller
@RequestMapping("/user/{userId}")
public class UserController {
    @RequestMapping("/{detailId}")
    public ModeAndView showDetail(@PathVariable("userId") String userId, @PathVariable("detailId") String detailId, Model model){
        ModeAndView mv = new ModelAndView();
        mv.setViewName("user/showdetail");     //to set a logic view name.
        mv.addObject("user", userService.getUserById(userId));   // add model data.
        return mv;
    }
}

Also, we can use request method, head, and params to map.

@RequestMapping(value="/user", method="RequestMethod.POST", params="userId", headers="content-type=text/*")
public String test(@RequestParam("userId") String userId){
    // do something
    return "user/test";
}

/**
* params="param1"; headers is the same as params.
* "param1": The request must contain a request param named "param1";
* "!param1": The request must not contain a request param named "param1";
* "param1 != value1": The request must contain a request named "param1" but its value can not be "value1";
* {"param1 = value1", "param2"}: The request must contain 2 params named "param1" and param2, and the value of param1 is "value1".
*/

@RequestParam("userName")
@RequestHeader("Accept-Language")
@CookieValue("sessionId")

@RequestMapping(value="/test")
public String test1(@RequestParams(value="userName", required=false, defaultValue="username") String username, @RequestParam("age") int age){
    // do something
}
/**
* @RequestParam
* value: the name of param; 
* required: true as default, means it must own a param name.
* defaultValue: when set, set required to false auto. Not recommend.
*
* @CookieValue, @RequestHeader have the same 3 values with @RequestParam.
*/

2. Model data

Control --> (produce) Model. View ---> (render) Model.
4 ways to output model data.

ModelAndView
@ModelAtrtibute
Map && Model
SesstionAttributes

1. ModelAndView
If the return statement of controller method is ModelAndView. Not only it contains view info, but also model data.
//Use the following methods to add model data.
ModelAndView addObject(String attributeName, Object attributeValue);
ModelAndView addAllObjects(Map<String, ?> modelMap);

//Use the following methods to set views.
void setView(View view);    // to set a concrete view object.
void setViewName(String viewName);   // to set a logic view name.
2. @ModelAttribute
// Use @ModelAttribtue in the in-param of methods.
@RequestMapping(value="test")
public String test(@ModelAtrtibute("user") User user){   // finally {"user": user} in model.
    user.setUserId("10");
    return "success";                  // success.jsp
}
/******************/
// Also, we can use @ModelAttribute in the definition of methods. 
@ModelAttribute("user")    // first executed before any methods of controller. 
public User getUser(){
    User user = new User();
    user.setUserId(100);
    return user;
}
// After executing the method above, we get a model data of {"user": user} in the model.

// Model data will pass to the in-param of User, and according to the http request data, user object will be fulfilled further.
@RequestMapping(value="/model")
public String handleModel(@ModelAttribute("user") User user){
    user.setUserName("tom");
    return "/user/success";
}

3. Map && Model
Model interface in Spring MVC, similar to Map in Java. 
ModelMap implements Map. ExtendedModelMap extends ModelMap and implements Model. 
Spring MVC will create a model object as data container for model data.

@ModelAttribute("user")
public User getUser(){
    User user  = new User();
    user.setUserId(100);
    return user;
}

@RequestMapping(value="/model")
public String handleModel(ModelMap modelMap){
    modelmap.addAttribute("testAttr", "value1");
    User user = (User) modelMap.get("user");      // *** attention ***
    user.setUserName("tom");
    return "/user/success";
}
4. SessionAttributes
// To Share model data among several http requests.
5. @PathVariable.  restful style
@Controller
@RequestMapping("/admin/{adminId}")
public class AdminLogin{
    @RequestMapping("login/{loginId}")
    public void login(@PathVariable("adminId") String adminId, @PathVariable("loginId") String loginId, Model model){

    }
}

3. What is View?

Different view has different implementation class.
A logic view(ModelAndView, logic name) needs a ViewResolver to convert it to view object(xxx.jsp, PDF, ...).

4. Data check(Spring MVC validation framework)

<bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

[Note: Not finished... Just for study.]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市周蹭,隨后出現(xiàn)的幾起案子趋艘,更是在濱河造成了極大的恐慌疲恢,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瓷胧,死亡現(xiàn)場離奇詭異显拳,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)搓萧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門杂数,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人瘸洛,你說我怎么就攤上這事揍移。” “怎么了反肋?”我有些...
    開封第一講書人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵那伐,是天一觀的道長。 經(jīng)常有香客問我石蔗,道長罕邀,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任抓督,我火速辦了婚禮燃少,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铃在。我一直安慰自己阵具,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開白布定铜。 她就那樣靜靜地躺著阳液,像睡著了一般。 火紅的嫁衣襯著肌膚如雪揣炕。 梳的紋絲不亂的頭發(fā)上帘皿,一...
    開封第一講書人閱讀 49,784評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音畸陡,去河邊找鬼鹰溜。 笑死,一個(gè)胖子當(dāng)著我的面吹牛丁恭,可吹牛的內(nèi)容都是我干的曹动。 我是一名探鬼主播,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼牲览,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼墓陈!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤贡必,失蹤者是張志新(化名)和其女友劉穎兔港,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體仔拟,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡衫樊,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了理逊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片橡伞。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖晋被,靈堂內(nèi)的尸體忽然破棺而出兑徘,到底是詐尸還是另有隱情,我是刑警寧澤羡洛,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布挂脑,位于F島的核電站,受9級(jí)特大地震影響欲侮,放射性物質(zhì)發(fā)生泄漏崭闲。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一威蕉、第九天 我趴在偏房一處隱蔽的房頂上張望刁俭。 院中可真熱鬧,春花似錦韧涨、人聲如沸牍戚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽如孝。三九已至,卻和暖如春娩贷,著一層夾襖步出監(jiān)牢的瞬間第晰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國打工彬祖, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留茁瘦,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓储笑,卻偏偏與公主長得像甜熔,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子南蓬,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理纺非,服務(wù)發(fā)現(xiàn),斷路器赘方,智...
    卡卡羅2017閱讀 134,629評(píng)論 18 139
  • =========================================================...
    lavor閱讀 3,484評(píng)論 0 5
  • In this tutorial, we will show you a Spring MVC hello wor...
    lovePython閱讀 588評(píng)論 0 1
  • 1烧颖、Spring MVC請(qǐng)求流程 (1)初始化:(對(duì)DispatcherServlet和ContextLoderL...
    拾壹北閱讀 1,946評(píng)論 0 12
  • 我在一家財(cái)產(chǎn)保險(xiǎn)公司上班,倒是不需要做什么業(yè)務(wù)窄陡,而且講財(cái)產(chǎn)保險(xiǎn)的時(shí)候人別人的反應(yīng)不會(huì)再像壽險(xiǎn)那樣反感炕淮,像:...
    胡姑娘閱讀 137評(píng)論 0 3