1.创建SpringBoot工程
1.1通过IDEA构建SpringBoot工程
新建工程,选择如图选项,下一步
选择所需要的组件,下一步,结束即可。
1.2通过网站构建SpringBoot工程
Spring项目初始化
https://start.spring.io/
生成工程,下载压缩包,解压导入即可。
2.最简单的HelloWorld
打开http://127.0.0.1:8080/即可看到HelloWorld。
3.参数解析
继续追加如下代码:
@RequestMapping(value = "/profile/{groupId}/{userId}")
@ResponseBody
public String profile(@PathVariable("groupId") String groupId,
@PathVariable("userId") int userId,
@RequestParam(value = "type", defaultValue = "1") int type,
@RequestParam(value = "key", defaultValue = "nowcoder") String key) {
return String.format("{%s},{%d},{%d},{%s}", groupId, userId, type, key);
}
这个就是前台传过来的PathVariable、RequestParam,我们后台用如上注解进行接收并打印。
4.使用velocity模板(相当于传统开发的Jsp)
继续追加
@RequestMapping("news")
public String news() {
return "news";
}
新建vm模板文件
5.后台传参到前台
@RequestMapping("news")
public String news(Model model) {
model.addAttribute("value1", "vv1");
return "news";
}
通过model来添加属性,velocity前台通过 $!{value1}就可以拿到参数了。
下面我们来学习一些常用velocity语法,更多自行百度谷歌或者官方:https://velocity.apache.org/engine/devel/user-guide.html。
6.Velocity模板语法
一、$!{ 变量/表达式 }
二、## 注释 ## #* 多行注释 *#
三、for循环:
#foreach ($color in $colors)
Color$!{foreach.count}/${foreach.index}:$!{color}
#end
四、属性访问
$!{user.name}
$!{user.getName()}
五、模板继承
include 纯文本扩展
parse 变量解析
六、macro
#macro (render_color, $color, $index)
This is Color $index:$color
#end
#foreach ($color in $colors)
#render_color($color, $foreach.index)
#end
7.结合例子学velocity语法
7.1 List
后端:
List<String> colors = Arrays.asList(new String[]{"RED", "GREEN", "BLUE"});
model.addAttribute("colors", colors);
前端:
#foreach ($color in $colors)
Color $!{foreach.index}/$!{foreach.count}: $!{color}
#end
Color 0/1: RED
Color 1/2: GREEN
Color 2/3: BLUE
7.2 Map
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; ++i) {
map.put(String.valueOf(i), String.valueOf(i * i));
}
model.addAttribute("map", map);
两种方法遍历map,与java语法类似
#foreach($key in $map.keySet())
Number $!{foreach.index}/$!{foreach.count}: $!{key} $map.get($key)
#end
#foreach($kv in $map.entrySet())
Number $!{foreach.index}/$!{foreach.count}: $!{kv.key} $!{kv.value}
#end
7.3 类
public class User {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
public User(String name) {
this.name = name;
}
}
model.addAttribute("user", new User("Jim"));
User:$!{user.name}
User:$!{user.getName()}
7.4 模板继承
ps:set用于设置属性
#set($title = "nowcoder")
Include: #include("header.vm") <br>
Parse:#parse("header.vm")
访问显示如下”
Include: Title $!title
Parse:Title nowcoder
我们可以知道include是包含,parse是包含还会进行解析。