zoukankan      html  css  js  c++  java
  • MVC架构中的controller的几种写法

    开始写代码之前,我们先来看一下spring MVC概念。一张图能够清晰得说明。

    除了controller,我们需要编写大量代码外,其余的都可以通过配置文件直接配置。

    MVC的本质即是将业务数据的抽取和业务数据的呈现分开来。controller是连接model和View的桥梁,在这一层,主要是业务逻辑的设置。

    ModelAndView有两种形式:Model 和 Map这使得在编写controller中的方法时也有两种参数形式。

    首先来看基础代码,这也常用的形式:

    //url: /user/show2?userId=123
        @RequestMapping(value = "/show2?userId",method = {RequestMethod.GET})
        public String showUser2(@RequestParam("userId")Integer userId,Model model){
            User user = userService.getUserById(userId);
            model.addAttribute(user);
            return "showUser";
        }

    比较传统的方式是使用HttpServletRequest,代码如下:

    //url:/user/show1?userId=123
        @RequestMapping("show1")
        public String showUser(HttpServletRequest request){
            int userId = Integer.parseInt(request.getParameter("userId"));
            User user = userService.getUserById(userId);
            request.setAttribute("user", user);
            return "showUser";
        }

    更为现代一点的方式是使用Map,同时url地址更为简洁,可以直接输入路径变量的值,而不需要再把路径变量也写出来。代码如下:

    //url: /user/show3/{userId}
        @RequestMapping(value = "/show3/{userId}",method = RequestMethod.GET)
        public String showUser3(@PathVariable("userId") Integer userId,Map<String,Object> model){
            User user = userService.getUserById(userId);
            model.put("user", user);
            return "showUser";
        }
  • 相关阅读:
    BOM-Window窗口对象
    BOM
    案例:电灯开关
    事件简单学习
    简单学习
    ECMAScript基本对象——Global全局对象
    ECMAScript基本对象——RegExp 正则表达式对象
    ECMAScript基本对象——String 对象
    zk安装管理
    kafka服务器批量copy文件脚本
  • 原文地址:https://www.cnblogs.com/sMKing/p/6029211.html
Copyright © 2011-2022 走看看