往作用域中放值-setAttribute方法

 1 @Controller
 2 public class UserController {
 3 
 4     //方法一:使用ModeAndView-addObject
 5     @RequestMapping(value = "ModelAndView")
 6     public ModelAndView modelAndView() {
 7         ModelAndView mode = new ModelAndView();
 8         mode.addObject("username", "admin");
 9         mode.setViewName("test");
10         return mode;
11     }
12 
13     //方法二:使用HttpServletRequest-->setAttribute
14     @RequestMapping(value = "request")
15     public String test(HttpServletRequest req) {
16         req.setAttribute("username", "admin");
17         return "test";
18     }
19 
20     //方法三:Model-->addAttribute
21     @RequestMapping(value = "Model")
22     public String test(Model model) {
23         model.addAttribute("username", "admin");
24         return "test";
25     }
26 
27     //方法四:Map-->put
28     @RequestMapping(value = "map")
29     public String test(Map<String, Object> map) {
30         map.put("username", "admin");
31         return "test";
32     }
33 }

前端jsp页面

1 <html>
2 <head>
3     <title>$Title$</title>
4 </head>
5 <body>
6 用户名是:${username}
7 </body>
8 </html>

运行结果

原文地址:https://www.cnblogs.com/lwl80/p/13817933.html