package com.example.demo.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
//@Controller跳转页面
@RequestMapping("/hello")
public String hello() {
System.out.println(1);
return "demo.html";
}
//ModelAndView仅跳转页面
@RequestMapping("/path1")
public ModelAndView test1() {
return new ModelAndView("h1.html");
}
//跳转并传递{key:value}
@RequestMapping("/path2")
public ModelAndView test2() {
return new ModelAndView("h2.html").addObject("hello", "world");
}
//跳转带map形式
@RequestMapping("/path3")
public ModelAndView test3() {
Map<String,Object> map=new HashMap<String,Object>();
map.put("foo", 1.5f);
map.put("bar", "hello");
return new ModelAndView("h4.html").addAllObjects(map);
}
//跳转带list套map形式
@RequestMapping("/path4")
public ModelAndView test4() {
Map<String,Object> map=new HashMap<String,Object>();
Map<String,Object> map2=new HashMap<String,Object>();
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
map.put("foo", 1.5f);
map.put("bar", "hello");
map2.put("foo", 123);
map2.put("bar", "world");
list.add(map);
list.add(map2);
return new ModelAndView("h3.html").addObject("list",list);
}
}
本例使用@Controller进行页面跳转,响应请求和JSON的形式见此系列其它文档
页面用Thymeleaf:
h1.html (略)
h2.html
<body>
<b th:text="${hello}"></b>
</body>
h3.html
<body>
<b th:text="${foo}" /><br>
<b th:text="${bar}" />
</body>
h4.html
<body>
<th:block th:each="row : ${list}" >
<b th:text="${row.foo}" />
<b th:text="${row.bar}" /><br>
</th:block>