02.SpringMVC传值【孔浩SpringMVC视频教程】学习笔记

来源:互联网 发布:mac如何把桌面的图标 编辑:程序博客网 时间:2024/04/30 09:08

接上篇:

把值传入控制器

package zttc.itat.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class HelloController{    //RequestMapping表示用哪个URL来对应    @RequestMapping{{"/hello","/"}}    public String hello(String username){           System.out.println("hello");           System.out.println("username");           return "hello";     }     @RequestMapping{{"/welcome"}}     public String welcome(){           System.out.println("welcome");           return "welcome";      } }

怎么把值传给视图呢?

package zttc.itat.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class HelloController{    //RequestMapping表示用哪个URL来对应    @RequestMapping{{"/hello","/"}}    public String hello(String username, Model model){           System.out.println("hello");           model.addAttribute("username", username);           System.out.println("username");           return "hello";     }     @RequestMapping{{"/welcome"}}     public String welcome(){           System.out.println("welcome");           return "welcome";      } }

但一般建议用下面这种方法:

package zttc.itat.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class HelloController{    //RequestMapping表示用哪个URL来对应    @RequestMapping{{"/hello","/"}}    public String hello(String username){           System.out.println("hello");           System.out.println("username",username);           System.out.println(username); //默认类型为string           return "hello";     }     @RequestMapping{{"/welcome"}}     public String welcome(){           System.out.println("welcome");           return "welcome";      } }


1 0
原创粉丝点击