Springboot的static和templates

Springboot的static和templates

SpringBoot里面没有我们之前常规web开发的WebContent(WebApp),它只有src目录

在src/main/resources下面有两个文件夹,static和templates springboot默认 static中放静态页面,而templates中放动态页面
在这里插入图片描述
静态页面:
这里我们直接在static放一个hello.html,然后直接输入http://localhost:8080/hello.html便能成功访问
(好像可以新建一个public文件夹,也可以放静态文件)
也可以通过controller跳转:

  @Controller
  public class HelloController {
      @RequestMapping("/Hi")
       public String sayHello() {
    return "hello.html";
  }
}

然后输入http://localhost:8080/Hi就可以成功访问

动态页面:

动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。
现在pom中要添加Thymeleaf组件

<dependency>  
  <groupId>org.springframework.boot</groupId>  
  <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency> 

我们先在tempates文件夹中也新建一个hello.html但内容不同,然后先试一下直接访问该页面。输入http://localhost:8080/hello.html:
在这里插入图片描述
结果显然访问的是静态问价夹里面的那个hello.html
然后我们现在再试一下用controller:
在这里插入图片描述
也就是我们要这样改controller:

@Controller
 public class HelloController {
@RequestMapping("/Hi")
public String sayHello() {
    return "hello";
 }
}

然后就可以成功跳转了

然后我们看看返回一点数据在前端利用Thyemleaf来拿:

 @Controller
  public class HelloController {
@RequestMapping("/Hi")
public ModelAndView sayHello() {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("hello");
    modelAndView.addObject("key", 12345);
    //System.out.println("test");
    return modelAndView;
 }
}
<html>
<head>
<meta charset="UTF-8"/>
<title>Insert title here</title>
</head>
<body>
<h1>this is the hello.html in templates</h1>
<span th:text="${key}"></span>  
</body>
</html>

效果:
在这里插入图片描述
如果不想返回视图,则用@RestController
如果用了静态模板你还想返回static中的页面,那么就要用重定向:
如果在使用动态页面时还想跳转到/static/index.html,可以使用重定向return “redirect:/index.html”。

return "redirect:hello.html";  

几点tips:

1.拦截的url最后不要跟视图重合,否则会抛出Circular view path异常,我之前就是

复制代码

 @Controller
 public class HelloController {
      @RequestMapping("/hello")
       public String sayHello() {
          return "hello.html";  
 }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值