美文网首页
Spring MVC

Spring MVC

作者: ibyr | 来源:发表于2016-09-15 11:47 被阅读18次

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

    相关文章

      网友评论

          本文标题:Spring MVC

          本文链接:https://www.haomeiwen.com/subject/hekbettx.html