zoukankan      html  css  js  c++  java
  • SpringMVC的值传递

    值的传递分为从页面传到到controller和从controller传递到页面,下面分别进行介绍:

      

    package com.springmvc.web;
    
    import java.util.Map;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class HelloController {
        
        @RequestMapping("test")
        public String test(@RequestParam("username")String username,Map<String, Object> map){
            map.put("username", username);
            return "test";
        }
        
        @RequestMapping({"/hello","/"})
        public String hello(String username,Map<String,Object> map){
            System.out.println("username==" + username);
            map.put("username", username);
            map.put("password", "222");
            return "hello";
        }
        
        @RequestMapping("/welcome")
        public String welcome(String username,Model model){
            System.err.println("username=" + username);
            model.addAttribute("username", username);
            model.addAttribute("password", "333333333");
            model.addAttribute(username);
            return "welcome";
        }
    }

     1.将参数传递给controller

      (1)利用@RequestParam来传递必须要的参数,并且将参数作为url的一部分进行传递。

    例如: http://127.0.0.1:8080/Spring_Hello/test?username=zhangsan,这样是可以接受到username的,但是请求的url中,username属性必须存在,否则会报

    HTTP Status 400 -   这里,是将参数当成了url的一部分.

      (2)不想将参数作为url的一部分,直接写参数即可,不需要RequestParam   

    2.将参数传递给页面

      (1) 在方法参数中放入一个Map<String,Object>,将需要传递给页面的参数以键值对的方式放入。在页面用${key }的方式取得数据。 如例 /hello

        (2) 也可以用spring推荐的方式,用model传递参数 如welcome,其中省略掉key的方式,默认key为value的数据类型。在传递对象类型数据时十分有用。如例 /welcome

      PS: model和map的区别还在于:利用map,参数是可以为空的;如果利用model,第一个参数username是必须要传递的。

  • 相关阅读:
    hadoop面试
    常用脚本
    1.kafka
    2.flink
    java面试
    Hbase 项目
    linux 2>&1 和 &的意思
    Jetbrains系列产品重置试用方法
    解决GitHub网页githubusercontent地址无法访问问题
    stylus 成熟的写法
  • 原文地址:https://www.cnblogs.com/Cilimer/p/3993987.html
Copyright © 2011-2022 走看看