zoukankan      html  css  js  c++  java
  • SpringMVc 随笔3 ,注解入参pathVariable,requestparam,和modelAttributes和返回值,modelAndView,map

    1.如果要从浏览器向控制器传入参数,有两个注解可以使用,一个是@PathVariable,一个是@RequestParam。

    其中,@PathVariable用于类似REST风格的入参,如/getEmp/12,这样子的。

    @RequestParam,用于/getEmp?user=xxx&password=xxx,这样的入参。

    示例如下,在注解中,如果只有一个参数,即value=,,默认的value可以省略不写

    package cn.taotao.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class EmployeeController {
        @RequestMapping("/getEmp")
        public String getEmp() {
            return "success";
        }
    
        @RequestMapping("/getEmp01/{id}")
         public String getEmp01(@PathVariable("id") Integer id) {
             System.out.println("id="+id);
            return "success";
         }
    
        @RequestMapping("/getEmp02") 
        public String getEmp02(@RequestParam("username") String username,@RequestParam("password") String password) {
            System.out.println("username= "+username+",pasword="+password);
            return "success";
        }
    }

    jsp页面如下

    <html>
    <body>
    <h2>Hello World!</h2>
    <a href="getEmp01/1332">get pathVariable</a>
    <br><br><br>
    <a href="getEmp02?username=xxxxx&password=765678">get RequestParam</a>
    <br>
    <br>
    <a href="getEmp">getEmp</a><br>
    </body>
    </html>

    返回值类型,有两个,最常用的是ModelAndView,另一个是Map,,系统会自动把map类型,或者list类型,封装成modelAndView类型。

    @RequestMapping("/testMap")
        public String testMap(Map<String, Object> map){
            System.out.println(map.getClass().getName()); 
            map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
            return "success";
        }
        
       
        @RequestMapping("/testModelAndView")
        public ModelAndView testModelAndView(){
            String viewName = "success";
            ModelAndView modelAndView = new ModelAndView(viewName);
            
         
            modelAndView.addObject("time", new Date());
            
            return modelAndView;
        }
        

     modelAttribute的属性是用来提前赋值的。比如修改一个表格,系统中有5个字段,但是表格中有4个字段,其他的一个,可能被置空,用上modelAttribute后,可以把数据库的提前读出来,不会被置空。

  • 相关阅读:
    C/S 随思录
    3dTiles 最后一块拼图:几何误差与屏幕空间误差
    aps.net cannot connect to runtime process
    asp.net web api swagger使用总结
    asp.net webaip 跨域
    LightGBM算法实践
    Zabbix 机器 CPU 飙高 和 时区相差8个小时
    【vue踩坑记录】3、“Error in render: "TypeError: Cannot read property '0' of undefined"”渲染错误问题
    1-关于补码的理解
    vscode快捷键
  • 原文地址:https://www.cnblogs.com/sdgtxuyong/p/11865310.html
Copyright © 2011-2022 走看看