springboot快速入门学习之论坛项目01(长期更新)

1 http://localhost:8887/hello?name=erenyegar中name=xxxxx 是传到服务器的参数,localhost:8887 是域名

	@GetMapping("/greeting")
	public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
	model.addAttribute("name", name);//通过name="name"接收value Sting name接收参数的值
	return "greeting";
    }
  • 此方法可以从浏览器获取接收的参数通过Model model内置类来传到页面上去
  • model.addAttribute相当于map,以K-value形式通过前端传的name来set到model里.
  • "greeting"是spring自带的模板引擎,return 字符串时会去工程中的templaties包中寻找html同名的文件渲染成网页

2.

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
//<html xmlns:th="http://www.thymeleaf.org">标签可以让spring去知道解析的模板是可支持的
//<p th:text="'Hello, ' + ${name} + '!'" />其中的${name}是用来替换上一段代码中k为name的内容

3.实际操作

  • 使用idea自带的Spring Initializr模块启动idea工程选择spring web自动配置.

      <!--在pom.xml添加此依赖-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
    
  • 编写Controller类:
    在工程栏中找到src文件中main文件的最后一级(在与xxApplication)中的包建一个Controller测试类

      @RestController
      public class HelloController {
    
      @RequestMapping("/hello")
      public String hello(String name){
          return "hello world!!!";
      }
      }
    
  • 在templates文件中xxxApplicationTests类中输入server.port=xxx(数字)即可设置域名,如没设置默认为localhost:8080

  • 启动此工程,打印日志完成后,在浏览器的网址栏中输入localhost:xxxx 白色页面显示"hello world!!!"即可完成初始网页的操作

发布了2 篇原创文章 · 获赞 7 · 访问量 243

猜你喜欢

转载自blog.csdn.net/qq_43536300/article/details/104079220