spring boot入门(二)

spring boot入门(二)

编写helloworld

一、使用@ResponseBody直接显示网页内容

1.创建项目

2… 引入依赖

在application.properties中添加以下依赖(只有这两个依赖),并保存:

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

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

3.书写controller层

在这里插入图片描述
在这里插入图片描述
@Controller:用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。

@RequestMapping:提供路由信息,负责URL到Controller中的具体函数的映射。

@ResponseBody:表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@esponsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@Responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用。

4.启动项目

在这里插入图片描述

点击运行此类:

在这里插入图片描述
在这里插入图片描述

5.浏览器访问

在这里插入图片描述

二、在html等文件中显示内容

1.添加依赖

在之上的基础上往里加依赖:

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

2.在application.properties中添加配置

spring.thymeleaf.cache=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

3.在相应路径下创建html文件(根据配置spring.thymeleaf.prefix=classpath:/templates/)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>Insert title here</title>
</head>
<body>
	 <div class="container">
    	<h2 th:text="${msg}"></h2>
    </div>
</body>
</html>

4.写控制器controller(同上)

@RequestMapping("hihi")
public String say(Map<String,Object> map) {
	map.put("msg", "hello world");
	return "hello";
}

return的返回值与html文件名相对应
配置文件中的spring.thymeleaf.suffix=.html自动匹配后缀名

5.运行项目(同上)

6.浏览器访问

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值