需求:向浏览发送/hello请求,并响应 Hello,Spring Boot 2
解决:
项目目录:controller层、Main启动项、pom.xml
controller层:写好逻辑跳转,当浏览器访问 localhost:8080/hello ,给浏览器返回“Hello SpringBoot2”,用到@RestController Main启动项:运行启动点,扫描同层目录,用到@SpringBootApplication pom.xml:引用web依赖、父依赖(提供默认依赖)
1、helloController (Controller类),标记 @RestController
/*
@RestController的作用等同于@Controller + @ResponseBody
1)
@Controller注解可以将该类交由spring管理,从而能够使用getBean()
或者@Autowired的方式从Spring中获取Bean实例。
@Controller标识的类,在语义上,表示该类代表控制器类。 2)@responseBody
@responseBody注解的作用是将controller的方法返回的
对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,
通常用来返回JSON数据或者是XML数据。
*/ @RestController
public class helloController {
@RequestMapping("/hello")
public String sayHello(){
return "hello SpringBoot2";
}
}
2、主类 MainApplication,运行启动点
/**
* @SpringBootApplication 标记为SpringBoot应用启动项
*/ @SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
3、pom.xml 只需要引入web依赖、父依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId>
<artifactId>helloSpringBoot2</artifactId>
<version>1.0-SNAPSHOT</version> <properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties> <!-- 指定父依赖为默认依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent> <dependencies>
<!-- 开发web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependencies>
</project>
用浏览器访问 localhost:8080/hello,结果如下:
开发中遇到的问题
报错1:Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean
原因:缺少注解 @SpringBootApplication
报错2:Maven 编译遇到 Process terminated
原因:xml文件标签重复、格式不规范